如何在 asp.net 核心中使用依赖注入在工作单元模式中延迟注入存储库

How to lazy inject repositories in unit of work pattern using dependency injection in asp.net core

我在我的 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 需要在存储库之间共享吗?这可能有助于消除紧密耦合。请协助。

尝试使用 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);
        }
    }
}