I am attempting to use the following Generic Repository Interface for DI and constructor injection:
public interface IRepository<TEntity> : IDisposable where TEntity : class
The problem is in order to define an instance of the Interface, I must provide the class type like this:
private IRepository<Person> _personRepository;
The issue with this is if I'm using DI (and I'm using Unity for IoC framework), then I have to define multiple instances in my constructor to get all repository interfaces I need to work with like this:
public MyClass(IRepository<Person> personRepository,
IRepository<Orders> ordersRepository,
IRepository<Items> itemsRepository,
IRepository<Locations> locationsRepository)
{
_personRepository = personRepository;
_OrdersRepository = ordersRepository;
_itemsRepository = itemsRepository;
_locationsRepository = locationsRepository;
}
Questions:
Please help clear this up for me, and I appreciate all your help!
Is this OK?
Sure. There's personal preference on whether to use constructor injection like you have or property injection. Constructor injection is cleaner since you don't have to have lot of parameters to your constructor, but it's safer as well.
what's the point of Unity to register Interface to concrete type
One reason is so that you can unit test MyClass
without having to use your actual repository that hits a database. You can "fake" out the repository to return hard-coded values to test against.