WebApi控制器继承自通用基础控制器?

时间:2015-05-05 12:50:46

标签: c# generics inheritance asp.net-web-api

在我的WebApi2项目中,我使用了存储库和UoW模式和服务模式。我有超过60个参考实体(例如客户类型,产品类别,标题,国家,银行代码等...),其中控制器始终具有相同的操作(获取,查找,创建,更新,删除)。然后,这些控制器将调用相应的服务方法。

其中一些控制器可能会有其他操作,具体取决于其型号,但基本操作始终可用且代码大致相同。

因此,以CustomerType实体为例,我有以下类:

com.washingtonpost.android.paywall.billing.amazon.AmazonIAPListener

其中:

CustomerType
CustomerTypeDto
CustomerTypeRepository : IRepository<CustomerType>
CustomerTypeError (enum)
CustomerTypeService : IEntityService<CustomerType>
CustomerTypeController

典型的控制器可能如下所示:

public interface IRepository<T> where T : class
{
    T Get(int id);
    Add(T entity);
    Update(T entity);
    Delete(T Entity);
}

public interface IEntityService<T>
{
    T Get(int id);
    Add(T entity);
    Update(T entity);
    Delete(T Entity);
}

我的问题是:

有一个基础通用控制器是否有意义,以便所有CRUD代码都位于那里,并且只在必要时重载方法?

此类通用控制器是否具有以下签名:

public class CustomerTypeController : ApiController
{
    private readonly ICustomerTypeService customerTypeService;

    public CustomerTypeController (ICustomerTypeService customerTypeService)
    {
        this.customerTypeService= customerTypeService;
    }

    public Task<IHttpActionResult> Create(CustomerTypeDto dto)
    {
        try
        {
            var entity = Mapper.Map<CustomerType>(dto);
            entity = customerTypeService.Save(entity);

            return Ok(Mapper.Map<CustomerTypeDto>(entity));
        }
        catch (ValidationException<CustomerTypeErrorEnum> vex)
        { }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }
}

0 个答案:

没有答案