Initizlizing a DbContext in a BaseController for MVC6 and EF7?

asp.net-core asp.net-core-mvc dependency-injection entity-framework-core

Question

Following the ASP.Net 5 Getting Started document I see that because of dependency injection at the top of any controller that will access the database I need to put something like

private DbContext _Context;

public HomeController(DbContext Context)
{
      _Context = Context;
}

to inject the DbContext into the controller for use. In my ASP.Net 5 MVC 6 Web App every single page will be interacting with the database so I thought I would create a BaseController that the reset of my controllers would inherit from and put the injection code there. I have done this but every controller that inherits from the BaseController give me the error

There is no argument given that corresponds to the required formal parameter 'Context' of 'BaseController.BaseController(DbContext)

I am new to DI and not sure if I am doing things right or even if it can be done the way I want to. Is it possible to do it this way or do I have to put that code on every controller I make, and if I do have to do that how can I write an action in the BaseController that interacts with the DB?

Accepted Answer

If your base controller has a constructor that takes DbContext then any controller that inherits it must also use the same constructor like this so it can pass the dependency to the base class:

public HomeController(DbContext Context):base(Context)
{

}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why