Reputation: 3397
Well in my ASP.NET MVC application all controllers use this ApplicationDbContext object. At this moment it is being instantiated inside controller constructor, but this is tight coupling and is not a good practice.
public MessagesController()
{
this.Db = new ApplicationDbContext();
this.Mapper = new MessageMapper(Db);
this.Service = new MessageService();
}
Ideally I want this ApplicationDbContext to be passed as a parameter to each controller's constructor, like this scenario with dependency injection:
public MessagesController(ApplicationDbContext context){
this.Db = context;
this.Mapper = new MessageMapper(Db);
this.Service = new MessageService();
}
The question is, how to achieve this? I tried to find the source code that controls controller dependency injection, but it comes as .NET dll file and I cannot modify(just like you cannot edit System namespace files). So how is dependency injection possible for controllers in ASP.NET MVC? Can anyone use my scenario as an example? Thanks.
Upvotes: 2
Views: 2315
Reputation: 8628
I'll give you my approach to this.
Off the bat, you don't want the DBContext exposed directly to the controller. Infact, to truly leave a seperation of concerns you dont want the controller to even know about a DbContext
at all.
If you where told that the company plan to start using a different storage technology, for example, RavenDB or MongoDB, each and every one fo your controllers would need refactoring. The DbContext
is no required or useful.
I dont know what the MessageMapper
class is, but it does take a DbContext
, and that too would break.
You need to look at adopting the Repository Pattern.
Read this article, it should help.
Upvotes: 0
Reputation: 10576
Install this package:
Install-Package Unity.Mvc5
In your Application_Start() add this line:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents(); // <----- Add this line
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
In UnityConfig register your type:
container.RegisterType<ApplicationDbContext>();
Done.
Update btw, by doing this you will just move the code that creates new object to Unity. Buy you are still waiting for concrete class. In addition you will have all the data manipulation operations in your controller (read: UI). If you really want to get rid of tight coupling you might want to take a look at DAO pattern. http://en.wikipedia.org/wiki/Data_access_object
Upvotes: 1