Search code examples
asp.net-mvc-4architecturedependency-injectionentity-framework-5data-access-layer

Decoupling ASP.MVC and data access layer with the dependency injection


I have an architectural issue. I'm trying to build an ASP.MVC web application using dependency injection to decouple data access layer. The problem is - models.

Basically I have two projects in solution. The first is the MVC web application and the second DLL which is data access layer. DAL has some interface, its implementation and models generated by Entity Framework, also some additional models - search criteria and results. MVC has a property in a base controller where the DAL is injected using Ninject.

My concern is - how should I handle the models?

Reason why I use the dependency injection is decoupling DAL from main web application. So if I properly understand the idea DAL should be easy attachable/detachable. But if I'd use DAL's models in MVC controllers and views it will be completely dependent on even slightest changes in the DAL.

I've created the models in MVC which duplicates Entity Framework generated models so I can use those MVC models in MVC and just before calling DAL methods I map them to the DAL models using AutoMapper, so the DAL models are used only in the controllers and coupling is looser. But it seems to be still dirty, far from elegance solution.

What do you think? Is there any way to handle it in a smarter way?


Solution

  • Put your models in a Common.dll which both the UI and DAL reference. If your DAL changes, you can make it return the existing models in Common without changing your UI. Or if you UI changes your new UI can just reference the Common.dll and work with existing models. If you later need to add an API, API will only reference the Common.dll (or whatever you want to call it).

    Edit: This is assuming you don't return EF models from your DAL to your UI. UI uses view models, DAL uses EF models, AutoMapper maps between the two.