Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Generic Repository with TEntity in Unity

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?

like image 575
Marco Avatar asked Aug 21 '14 07:08

Marco


People also ask

What is the right way to include a repository into a controller?

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.

What is generic repository in C#?

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.

Is Entity Framework a repository pattern?

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.


1 Answers

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)

like image 139
Daniel J.G. Avatar answered Oct 06 '22 05:10

Daniel J.G.