0

我正在使用 WCF Web Api preview 5 开发一个 web api。目前我有一个功能齐全的资源类,但我如何注意到我在这个资源中的方法变得越来越复杂。

例如:

[WebInvoke(UriTemplate = "{EhrID}/PhysicalTest",Method="POST")]
    public HttpResponseMessage<DTO.PhysicalTest> PostPhysicalTest(int EhrID, DTO.PhysicalTest PhysicalTestDTO)
    {
        var EHR = repository.FindById(EhrID);
        var PhysicalTest = Mapper.Map<DTO.PhysicalTest, PhysicalTest>(PhysicalTestDTO);

        if (PhysicalTest == null)
        {                
            var response = CreateResponseForException("No object to store", HttpStatusCode.BadRequest);
            throw new HttpResponseException(response);
        }

        try
        {
            if (EHR.PhysicalTests == null)
            {
                EHR.PhysicalTests = new List<PhysicalTest>();
            }
            PhysicalTest.CreationDate = DateTime.Now;
            EHR.PhysicalTests.Add(PhysicalTest);
            _unitOfWork.Commit();
            return new HttpResponseMessage<DTO.PhysicalTest>(PhysicalTestDTO, HttpStatusCode.Created);
        }
        catch (Exception ex) {                
            var response = CreateResponseForException("Cannot create Physical Test", HttpStatusCode.InternalServerError);
            throw new HttpResponseException(response);
        }
    }

正如您可能注意到的那样,此方法的任务是发布新的物理测试,但它实际上也在验证我的模型(我仍然缺少很多验证,属性验证),这不应该是此类关注的问题。是否有任何可行的方法来降低资源内方法的复杂性?

4

1 回答 1

0

我会把它分成更小更集中的方法。我也可能开始使用实例变量,而不是传递所有这些参数,但为了这篇文章,我已经重写了它,没有将东西推送到实例变量。

[WebInvoke(UriTemplate = "{EhrID}/PhysicalTest",Method="POST")] 
public HttpResponseMessage<DTO.PhysicalTest> PostPhysicalTest(int EhrID, DTO.PhysicalTest PhysicalTestDTO) 
{ 
    var EHR = repository.FindById(EhrID); 
    var PhysicalTest = Mapper.Map<DTO.PhysicalTest, PhysicalTest>(PhysicalTestDTO); 

    if (PhysicalTest == null) 
    {                 
        var response = CreateResponseForException("No object to store", HttpStatusCode.BadRequest); 
        throw new HttpResponseException(response); 
    } 

    PostPhysicalTest(EHR, PhysicalTest);
    return new HttpResponseMessage<DTO.PhysicalTest>(PhysicalTestDTO, HttpStatusCode.Created);
}

private void PostPhysicalTest(EHR ehr, PhysicalTest physicalTest)
{
    try 
    { 
        CreatePhysicalTest(ehr, physicalTest);
    } 
    catch (Exception ex) {                 
        var response = CreateResponseForException("Cannot create Physical Test", HttpStatusCode.InternalServerError); 
        throw new HttpResponseException(response); 
    }
}

private void CreatePhysicalTest(EHR ehr, PhysicalTest physicalTest)
{
    if (ehr.PhysicalTests == null) 
    { 
        ehr.PhysicalTests = new List<PhysicalTest>(); 
    }

    physicalTest.CreationDate = DateTime.Now; 
    ehr.PhysicalTests.Add(physicalTest); 
    _unitOfWork.Commit();
}
于 2011-11-01T20:15:42.593 回答