Question: Initizlizing a DbContext in a BaseController for MVC6 and EF7?

Question

Initizlizing a DbContext in a BaseController for MVC6 and EF7?

Answers 1
Added at 2016-01-15 19:01
Tags
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?

Answers to

Initizlizing a DbContext in a BaseController for MVC6 and EF7?

nr: #1 dodano: 2016-01-15 19:01

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)
{

}
Source Show
◀ Wstecz