Generic Repositories with DI & Data Intensive Controllers
- by James
Usually, I consider a large number of parameters as an alarm bell that there may be a design problem somewhere. I am using a Generic Repository for an ASP.NET application and have a Controller with a growing number of parameters.
public class GenericRepository<T> : IRepository<T> where T : class
{
protected DbContext Context { get; set; }
protected DbSet<T> DbSet { get; set; }
public GenericRepository(DbContext context)
{
Context = context;
DbSet = context.Set<T>();
}
...//methods excluded to keep the question readable
}
I am using a DI container to pass in the DbContext to the generic repository. So far, this has met my needs and there are no other concrete implmentations of IRepository<T>. However, I had to create a dashboard which uses data from many Entities. There was also a form containing a couple of dropdown lists. Now using the generic repository this makes the parameter requirments grow quickly.
The Controller will end up being something like
public HomeController(IRepository<EntityOne> entityOneRepository,
IRepository<EntityTwo> entityTwoRepository,
IRepository<EntityThree> entityThreeRepository,
IRepository<EntityFour> entityFourRepository,
ILogError logError,
ICurrentUser currentUser)
{
}
It has about 6 IRepositories plus a few others to include the required data and the dropdown list options. In my mind this is too many parameters. From a performance point of view, there is only 1 DBContext per request and the DI container will serve the same DbContext to all of the Repositories. From a code standards/readability point of view it's ugly.
Is there a better way to handle this situation? Its a real world project with real world time constraints so I will not dwell on it too long, but from a learning perspective it would be good to see how such situations are handled by others.