Ninject: Entity context for the controller

I know that a thousand questions have been asked related to this topic, but I went through at least a dozen and still do not connect the dots. I am trying to configure dependency injection for entity contexts.

I always created an entity context, as I saw in MS textbooks, for example:

public class UserController : Controller
{
    private DbEntities db = new DbEntities();

}

A recent reading told me that this is no longer (if it has ever been) the best practice, and a dependency injection method should be used. Ninject is often mentioned, but I see how you go from what I have, for example, give Ninject documentation .

It should look like this when I'm done, right?

public class UserController : Controller
{
    private DbEntities db;

    public UserController(DbEntities context)
    {
        db = context;
    }
}

" , ". , . Nuget , , , : " RegisterServices". , ? .

, - , , .

+5
3

Nuget , , : " RegisterServices." , ?

Nuget . , Ninject factory, , Ninject , .

App_Start, NinjectMVC3.cs. RegisterServices(), .

DbEntities. :

kernel.Bind<DbEntities>().ToSelf();

, , Entity Framework, IoC, .

- , , . Ninject MVC3 github.

+4

, .

"" factory, . , Ninject kernel.Bind() factory. kernel.Bind<DbEntities>().ToSelf(), , Ninject (DbEntities ) , . :

var entities = kernel.Get<DbEntities>();  // Note: don't do this, just an example

, , . factory, .

, , . Injection Dependency , . , , , DbEntities. , DI Framework, DbEntities. . . MyController , DbEntities (, DbEntities DI)

var controller = kernel.Get<MyController>();

public class MyController : Controller {
    private DbEntities _entities;
    public MyController(DbEntities entities) {
        _entities = entities;
    }
}

. , , - , get, , .. .., , , , .

MVC , DI . kernel.Get, , . IDependencyResolver , MVC DI , .

Ninject Nuget Ninject.MVC3, , RegisterServices() NinjectMVC3.cs

, , . Dependency Injection , , , , , , MVC . .

EDIT:

, . , DI. , Get() "Location " . , , - , - Get(), .

, , .

+1

All Articles