I’m going round in circles at the moment trying to get the pattern right for using Dependency Injection with a number of IEnumerables.
I have three types of object that I want to return from my database: Projects, Batches and Tasks. I want to create a Repository that has the following form:
public interface IRepository<T>
{
IEnumerable<T> GetAll();
IEnumerable<T> GetAllActive();
IEnumerable<T> GetItemsByUserName(string UserName);
T GetItemById(int ID);
}
So when I create a concrete implementation of a ProjectRepository, it will look like this:
IEnumerable<Project> GetAll();
IEnumerable<Project> GetAllActive();
IEnumerable<Project> GetItemsByUserName(string UserName);
Project GetItemById(int ID);
And similarly for Tasks:
IEnumerable<Task> GetAll();
IEnumerable<Task> GetAllActive();
IEnumerable<Task> GetItemsByUserName(string UserName);
Task GetItemById(int ID);
My difficulty is in trying to declare an IRepository in my calling code. When I declare the reference, I find myself needing to declare a type:
private IRepository<Project> Repository;
…which is of course pointless. I’m going wrong somewhere but can’t get my head around it at the moment. How do I use dependency injection so that I can declare an interface that makes use of all three concrete types?
Hope I’ve explained myself properly.
Use generics:
Of course, at some point you need to provide
T, which might look like this:In terms of registering your types with your DI container, it may be useful if your DI container supports open generics. For example, check out this post that shows how Unity supports this.