Using Ninject with ASP.NET MVC 3 dependency injection

Ninject is my favorite container for doing dependency injection. However, it always seemed a bit complicated to use with ASP.NET WebForms.

Things have improved with ASP.NET MVC 1 of course but now, with the release of ASP.NET MVC 3, things have become way easier to do.

Here is what my Global.asax.cs looks like when I want to register an IoC tool for ASP.NET MVC 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protected void Application_Start()
{

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
RegisterDependencyResolver();
}

private void RegisterDependencyResolver()
{

var kernel = new StandardKernel();

DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

Well that look easy enough no? Well, to be fair… NinjectDependencyResolver doesn’t exist. It’s a custom class that I created to allow the easy mapping of the Kernel.

The only thing it needs is the Ninject StandardKernel. Once all the mappings are done, we give the kernel to the resolver and let MVC handle the rest.

Here is the code for NinjectDependencyResolver for all of you to use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class NinjectDependencyResolver : IDependencyResolver
{
private readonly IKernel _kernel;

public NinjectDependencyResolver(IKernel kernel)
{

_kernel = kernel;
}

public object GetService(Type serviceType)
{

return _kernel.TryGet(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _kernel.GetAll(serviceType);
}
catch (Exception)
{
return new List<object>();
}
}
}