In a previous article, we setup a simple ASP.NET MVC project and added references to Entity Framework as well as a dependency injector called Ninject.
What does this dependency injector give us?
Let's take a look at an example.
You have 2 controllers in your ASP.NET MVC project, the first is used to administrate your films and the other is to administrate your actors. In each of the controllers, you have a dependency of a DbContext.
How do you handle this scenario? You could create it and cache it, but then you need to write some code to retrieve it.
That's what Dependency Injectors are there for. That's what Ninject is there for, so let's see how it will make the magic happen. In the previous post we added the references using nuget and now we are going to use them.
Ninject expects you to register modules with the Kernel. Modules are little units that inform ninject of what dependencies you want to register and how you want them constructed and configured.
e.g.
/// <summary>
/// Database Module
/// </summary>
public class Database : NinjectModule
{
/// <summary>
/// Load
/// </summary>
public override void Load()
{
Bind<IObjectContextAdapter>().To<MovieContext>().InRequestScope();
}
}
In the App_Start folder/directory that Ninject created when it was installed, navigate over to the RegisterServices inside of the NinjectMVC3.cs file. We are going to ask Ninject to register all the modules located in the executing assembly.
e.g.
kernel.Load(Assembly.GetExecutingAssembly());
Ninject is all ninjad up and ready to go, inside a controller, let's add a constructor and give it a DbContext as a parameter.
e.g.
public class FilmController : Controller
{
private MovieContext db;
public FilmController(IObjectContextAdapter movieContext)
{
db = movieContext as MovieContext;
}
Shakes head, that wasn't difficult was it? That's called Constructor Dependency Injection
In the next tutorial, we will look at not strongly typing your views to your data model, but to an intermediary object called a ViewModel.
Read More

