fingers10
fingers10

Reputation: 7937

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

I'm using UnitOfWork in my asp.net 5 project as shown below:

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);
        }
    }
}

Is there any way to lazy inject my CategoryRepository : IAsyncRepository or ItemRepository : IAsyncRepository using dependency injection in such a way that it will only be instantiated only when I'm accessing the particular repository and also same DbContext needs to be shared between Repositories? This could help to remove the tight coupling. Please assist.

Upvotes: 1

Views: 1894

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

Try to use IServiceProvider for such task.

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);
        }
    }
}

Upvotes: 1

Related Questions