【发布时间】:2020-01-11 23:19:58
【问题描述】:
为了避免 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);
}
【问题讨论】:
-
使用依赖注入将服务注入控制器。使用 autofac 之类的工具来解决依赖关系
标签: c# generics .net-core repository-pattern