使用通用存储库的依赖注入

时间:2017-01-26 22:39:13

标签: c# generics dependency-injection asp.net-core .net-core

我正在尝试在我的web api控制器中执行依赖注入(ASP.NET CORE),但是我遇到了问题,因为它有一个包含工作单元的通用存储库,还有一个通用的服务层。这些服务位于不同的类库中。存储库也是如此。

我正在显示我的代码:

    public class AccountController : Controller
   {
     private IAccountService _accountService;

   public AccountController(IAccountService accountService)
    {
        _accountService = accountService;
    }
   }

服务层(基础服务):

  public class BaseService<TEntity> : IDisposable, IBaseService<TEntity> where TEntity : class
{
    private readonly IBaseRepository<TEntity> _repository;
    private readonly IUnitOfWork _unitOfWork;

    public BaseService(IBaseRepository<TEntity> repository, IUnitOfWork unitOfWork)
    {
        _repository = repository;
        _unitOfWork = unitOfWork;
    }

帐户服务:

public class AccountService : BaseService<User>, IAccountService
{
    private readonly IAccountRepository _repository;
    private readonly IUnitOfWork _unitOfWork;

    public AccountService(IAccountRepository repository, IUnitOfWork unitOfWork) : base (repository, unitOfWork)
    {
        _repository = repository;
        _unitOfWork = unitOfWork;
    }

基础资料库:

  public class BaseRepository<TEntity> : IDisposable, IBaseRepository<TEntity> where TEntity : class
{
    protected NeoSpaceDbContext _database;

    public BaseRepository(NeoSpaceDbContext database)
    {
        _database = database;
    }

帐户存储库:

public class AccountRepository : BaseRepository<User>, IAccountRepository
{
    public AccountRepository(NeoSpaceDbContext context) : base(context)
    {} 
}

我认为我的问题是我的网络API中的启动配置。

我已经尝试过了:

 services.AddScoped(typeof(IBaseService<User>), typeof(AccountService));

        services.AddScoped(typeof(IBaseService<>), typeof(BaseService<>));
        services.AddSingleton<IAccountService, AccountService>();

但没有任何作用...... 有人能告诉我我的案例的正确配置是什么吗?

1 个答案:

答案 0 :(得分:0)

我想你不需要

services.AddScoped(typeof(IBaseService<>), typeof(BaseService<>));

因为IAccountService应该实现IBaseService<> 并且AccountService应该实现BaseService<>。因此您无需解析IBaseService

services.AddScoped<IAccountService, AccountService>();

应该工作