The other day found myself hammering key strokes at Google to determine the best way to setup Ninject 3.0 for ASP.NET MVC 4 Web API project. After reading a few articles regarding complex options in the end it was quite simple really. Using Ninject 3.0 NuGet package makes things much simpler as DynamicModuleUtility configuration wiring mentioned in Shawn Wildermuth’s blog post Web API and Ninject is already done in the App_Start/NinjectWebCommon.cs class. By default Ninject container is setup for ASP.NET MVC 4 to add the container to Web API one additional step is required. Add the following code to CreateKernal method.
//usingSystem.Web.Http;//usingyammer.analytics.Infrastruture.Logging;[assembly: WebActivator.PreApplicationStartMethod(typeof(yammer.analytics.App_Start.NinjectWebCommon), "Start")][assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(yammer.analytics.App_Start.NinjectWebCommon), "Stop")]namespaceyammer.analytics.App_Start{usingSystem;usingSystem.Web;//usingMicrosoft.Web.Infrastructure.DynamicModuleHelper;//usingNinject;usingNinject.Web.Common;publicstaticclassNinjectWebCommon{privatestaticreadonlyBootstrapperbootstrapper=newBootstrapper();/// <summary>/// Starts the application/// </summary>publicstaticvoidStart(){DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));bootstrapper.Initialize(CreateKernel);}/// <summary>/// Stops the application./// </summary>publicstaticvoidStop(){bootstrapper.ShutDown();}/// <summary>/// Creates the kernel that will manage your application./// </summary>/// <returns>The created kernel.</returns>privatestaticIKernelCreateKernel(){varkernel=newStandardKernel();kernel.Bind<Func<IKernel>>().ToMethod(ctx=>()=>newBootstrapper().Kernel);kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();RegisterServices(kernel);GlobalConfiguration.Configuration.ServiceResolver.SetResolver(t=>kernel.TryGet(t),t=>kernel.GetAll(t));returnkernel;}/// <summary>/// Load your modules or register your services here!/// </summary>/// <param name="kernel">The kernel.</param>privatestaticvoidRegisterServices(IKernelkernel){kernel.Bind<ILogger>().To<NLogger>();}}}