Travis J
Travis J

Reputation: 82267

ASP.NET MVC 3 Implementing Unit Of Work using DI and Repository with EF

So, I am trying to implement best practices during the design phase of a system. I am going to be using a DI container (ninject) with Entity Framework 4, ASP.NET MVC 3 C#, and the repository / unit of work pattern.

  • I am going to have models where each database's tables are mapped to classes.
  • I am going to have a connection string for each database in web.config.
  • I am going to have a class for each connection string (named the same using EF convention) which inherits from DbContext and has a DbSet for each table.
  • I am going to have an abstract repository interface for each database entity named by convention ITRepository where T is the name of the DataBase entity (ICarRepository for database entity Car). Each repository interface will hold an IQueryable for the entity and also define what methods should be exposed.
  • I am going to have a concrete repository EFTRepository which inherits from ITRepository and defines how the exposed methods work.
  • I am going to have a GenericRepository<TEntity> defined for use with entities that require only minimal access such as basic CRUD.
  • I am going to use a ControllerFactory from ninject as a DI container.
  • I am going to attach the ninject controller factory in Application_Start().
  • I am going to bind all my dependencies, such as Bind<ITRepository>().To<EFTRepository>() in the factory's AddBindings() method.
  • I am going to implement a Unit Of Work pattern for each database and keep to naming conventions UnitOfWorkDB (UnitOfWorkAutomobile for database Automobile).
  • The Unit Of Work will hold the relevant database context and repositories.
  • Am I going about this right? I haven't used this set of patterns before and want to make sure I am going to be using them correctly. Criticisms welcome!

    Upvotes: 3

    Views: 1420

    Answers (1)

    Adam Tuliper
    Adam Tuliper

    Reputation: 30152

    Inheriting from a base repository can provide some simple 'generic' functions but in other situations you'll quickly find out it becomes messy trying to have a generic based repository (assuming that was what was inheriting).

    Everything else you described seems pretty good.

    You didn't say what was going to be injected where though, I'm assuming you will be injecting a service, the service will take a unit of work (IUnitOfWork for ex., created as a per request instance) and an IWhateverRepostory

    Upvotes: 3

    Related Questions