Ninject vs. MEF for ASP.NET MVC Apps
April 23, 2010 in ASP.NET MVC
This week I have been looking at using a dependency injection container for an MVC 2 application. Since I am using .NET Framework 4 with Managed Extensibility Framework (MEF) built in, it is one option to consider. I have also heard good things about Ninject. So lets do a quick comparison between Ninject and MEF with the simplest of implementations.
Ninject
To start off, I downloaded the .NET Framework 3.5 release of Ninject assembly and then reference that as I recompile the Ninject.Web.MVC assembly for .NET 4. Then I created a new ASP.NET MVC 2 project and reference those assemblies:
Next I modified the MvcApplication class in Global.asax.cs to inherit from NinjectHttpApplication and use the OnApplicationStarted and CreateKernal overrides to wire Ninject
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
RegisterAllControllersIn(Assembly.GetExecutingAssembly());
}
protected override IKernel CreateKernel()
{
var modules = new INinjectModule[]
{
new WebModule()
};
return new StandardKernel(modules);
}
To associate an interface to an implementation, I create a WebModule class that inherits from NinjectModule:



