I am learning how to use the Unity Framework for Dependency Injection in asp.net MVC 5 projects.
In general, I would set up a mapping for my repositories like this:
public static void RegisterComponents()
{
var container = new UnityContainer();
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IModelRepository, ModelRepository>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
Is it possible to do this with a generic Repository which looks like this:
public class GenericRepository<TEntity>
: IGenericRepository<TEntity> where TEntity : class
{ /* ... */ }
Out of instinct I would set up and register this like this:
container.RegisterType<IGenericRepository<TEntity>, GenericRepository<TEntity>>();
which does not work.
Do I need to register a Generic Repository for every model type like this?
container.RegisterType<IGenericRepository<Model1>, GenericRepository<Model1>>();
container.RegisterType<IGenericRepository<Model2>, GenericRepository<Model2>>();
container.RegisterType<IGenericRepository<Model3>, GenericRepository<Model3>>();
...
container.RegisterType<IGenericRepository<Model_N>, GenericRepository<Model_N>>();
Or is there a way to inject this repository once for all model classes and controllers?
By taking advantage of dependency injection (DI), repositories can be injected into a controller's constructor. the following diagram shows the relationship between the repository and Entity Framework data context, in which MVC controllers interact with the repository rather than directly with Entity Framework.
It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source.
Entity Framework already implements a repository pattern. DbContext is your UoW (Unit of Work) and each DbSet is the repository. Implementing another layer on top of this is not only redundant, but makes maintenance harder. People follow patterns without realizing the purpose of the pattern.
You can register the generic types for any TEntity this way:
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
See the msdn on Unity 2.1 or Unity 3 (Registering Open Generics section)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With