Getting Ninject to work with MVC 3 has just gotten a whole lot easier. With only 1 DLL reference (Ninject.dll, version 2.1.0.76 or greater, which can be obtained through NuPack) and one local class, you can have your application up and running with all the dependency injection you could ever want.
First, add a reference to Ninject.dll. That was easy. (If you used NuPack then it was even easier.)
Next, add the following class.
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication1.Lib;
using Ninject;
namespace MvcApplication1
{
public class NinjectResolver : IDependencyResolver
{
private readonly static IKernel _kernel = new StandardKernel();
public NinjectResolver()
{
RegisterServices(_kernel);
}
public object GetService(Type serviceType)
{
return _kernel.Get(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.GetAll(serviceType);
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IMyService>().To<MyServiceImpl>();
}
}
}
The only thing left to do now is to register the new IDependencyResolver with the application. You do that in the in the global.asax file.
protected void Application_Start()
{
// Put anything else you might need in Application_Start()
// Add the following line to set the dependency resolver.
DependencyResolver.SetResolver(new NinjectResolver());
}
See, I told you it was easy.