通用基本控制器中的通用服务

问题描述 投票:0回答:1

为了避免DRY,我大胆尝试为所有控制器生成通用基类的想法。一切正常,直到插入服务类为止。我的基本控制器是:

basecontroller.cs

public class BaseController<TEntity, Tdto, TKey> : Controller
{
    protected TavoraContext _context;
    protected IMapper _mapper;

    private IGeneric<TEntity, TKey, Tdto> _srv;

    public BaseController(IGeneric<TEntity, TKey, Tdto> srv)
    {
        _srv = srv;
    }

然后,在其中一个控制器中:

companiescontroller.cs

public class CompaniesController : BaseController<Company, CompanySimpleDTO, long>
{

    public CompaniesController(TavoraContext context, IMapper mapper, CompaniesService companiesService) : base(companiesService)
    {
    }

CompaniesService继承自实现IGeneric的GenericService,因此,我认为应该没有错误,并且我得到'不可能从CompaniesService转换为IGeneric']

companiesservice.cs

public class CompaniesService : GenericService<Company, long, CompanyDTO>
{

    public CompaniesService(TavoraContext context, IMapper mapper)  : base(context, mapper)
    {

        _runner = new RunnerWriteDb<CompanyDTO, Company>(
            new WriteCompanyAction(
                new WriteCompanyDBAccess(context), mapper), context);

    }

genericservice.cs

public class GenericService<TEntity, TKey, Tdto> : IGeneric<TEntity, TKey, Tdto> where TEntity : BaseEntity<TKey>
{
    protected RunnerWriteDb<Tdto, TEntity> _runner; 

    protected readonly int PAGESIZE = 20;
    protected readonly TavoraContext _context;
    protected DbSet<TEntity> _currentEntity;
    protected IMapper _mapper;

    public GenericService(TavoraContext context, IMapper mapper)
    {
        _context = context;
        _currentEntity = _context.Set<TEntity>();
        _mapper = mapper;
    }

IGeneric.cs

public interface IGeneric<TEntity, TKey, Tdto>
{
    IQueryable<TEntity> GetAll();
    IQueryable<DTO> GetAll<DTO>();

    //void Add(TEntity newItem);
    //void AddRange(List<TEntity> newItems);

    bool Update(TEntity updateItem);
    void UpdateRange(List<TEntity> updateItems);

    bool Delete(TKey id);
    bool DeleteRange(List<TEntity> removeItems);

    TEntity GetById(TKey id);

    RunnerWriteDbResult<TKey> Write(Tdto dto);
}

为了避免DRY,我大胆尝试为所有控制器生成通用基类的想法。一切正常,直到插入服务类为止。我的基本控制器是:...

c# generics .net-core repository-pattern
1个回答
-1
投票

使用依赖注入将服务注入控制器。使用类似autofac的pkgs来解决依赖关系

© www.soinside.com 2019 - 2024. All rights reserved.