【问题标题】:How to lazy inject repositories in unit of work pattern using dependency injection in asp.net core如何使用 asp.net 核心中的依赖注入在工作单元模式中延迟注入存储库
【发布时间】:2021-10-23 01:45:25
【问题描述】:

我在我的asp.net 5 项目中使用UnitOfWork,如下所示:

public class UnitOfWork : IUnitOfWork
{
    private readonly BaseContext _context;
    private IAsyncRepository<CategoryEntity> _categoryRepository;
    private IAsyncRepository<ItemEntity> _itemRepository;

    public UnitOfWork(BaseContext context)
    {
        _context = context;
    }

    public IAsyncRepository<CategoryEntity> CategoryRepository
    {
        get
        {
            return _categoryRepository ??= new CategoryRepository(_context);
        }
    }

    public IAsyncRepository<ItemEntity> ItemRepository
    {
        get
        {
            return _itemRepository ??= new ItemRepository(_context);
        }
    }
}

有没有办法lazy inject 我的CategoryRepository : IAsyncRepositoryItemRepository : IAsyncRepository 使用依赖注入,只有在我访问特定存储库时才会实例化它,并且同样需要DbContext在存储库之间共享?这可能有助于消除紧密耦合。请帮忙。

【问题讨论】:

  • 这种设计有其挑战。依赖关系应该是相反的。存储库需要依赖于工作单元,否则需要工厂抽象,这可能会使设计更加复杂。
  • this 方法适用于您使用的容器

标签: c# asp.net-core dependency-injection entity-framework-core unit-of-work


【解决方案1】:

尝试使用IServiceProvider 完成此类任务。

public class UnitOfWork : IUnitOfWork
{
    private readonly BaseContext _context;
    private readonly IServiceProvider _provider;
    private IAsyncRepository<CategoryEntity> _categoryRepository;
    private IAsyncRepository<ItemEntity> _itemRepository;

    public UnitOfWork(BaseContext context, IServiceProvider provider)
    {
        _context = context;
        _provider = provider;
    }

    private T InitService<T>(ref T member)
    {
        return member ??= _provider.GetService<T>();
    }

    public IAsyncRepository<CategoryEntity> CategoryRepository
    {
        get
        {
            return InitService(ref _categoryRepository);
        }
    }

    public IAsyncRepository<ItemEntity> ItemRepository
    {
        get
        {
            return InitService(ref _itemRepository);
        }
    }
}

【讨论】:

  • _context 怎么样?它会在存储库之间共享吗?
  • 如果上下文注册为Scoped,是的。
  • link 中的这个惰性实现怎么样?这是一个好方法吗?
  • 也是一种有趣的方法。但是线程安全在这里是多余的。
  • 这个工作单元现在已成为存储库工厂。我知道 OP 示例很可能是最小的,但如果上下文没有明确地与单元一起使用,那么它可以被删除,因为它会在解析时被注入到存储库中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2018-08-30
  • 2021-11-10
  • 1970-01-01
  • 2010-12-10
相关资源
最近更新 更多