I am aware that a thousand and one questions relating to this topic have been asked, but I have gone through at least a dozen and am still not connecting the dots. I am trying to setup dependency injection for entity contexts.
I have always created my entity context as I have seen in the MS tutorials, like so:
public class UserController : Controller
{
private DbEntities db = new DbEntities();
}
Recent reading has told me that this is no longer (if it ever was) the best practice, and a dependency injection method should be used. Ninject is mentioned often, but I am seeing how you move from what I have, to the example give in the Ninject documentation.
It should look like this when I am done, right?
public class UserController : Controller
{
private DbEntities db;
public UserController(DbEntities context)
{
db = context;
}
}
The documentation starts out with “In the previous step we already prepared anything that is necessary for controller injection.” which is confusing as hell, since the previous step was installation. I used the Nuget method to install, but I don’t know what it means when it says “Now load your modules or define bindings in RegisterServices method.” How do I do that, and is entity a module or a binding? The documentation feels so sparse.
I am sorry if I skipped over something critical in the docs, I’ve been bouncing between forums for hours trying to figure out this one step.
The Nuget installation actually does quite a lot of things for you already. The most important thing is that it sets up Ninject as controller factory, which means that Ninject will create your controllers and is able to pass in all dependencies you have registered with it.
If you check the App_Start folder you will find a file
NinjectMVC3.cs. There is already an empty methodRegisterServices()which you can use to register your dependencies.For your example you must be able to resolve
DbEntities. The easiest most basic way to do this is:That said you really should pass in an interface to your controller so the controller does not depend on Entity Framework, using abstractions and registering a concrete class to use in the IoC container is one of the main reasons for dependency injection.
This should give you a start – the documentation you link to seems a bit outdated. I would recommend looking at the Ninject MVC3 sample on github.