Set up Ninject in Web API 2 in Visual Studio 2015.

Use Nuget package manager to download these two packages.

  1. Ninject.Web.WebApi for API 2
  2. Ninject.Web.Common.WebHost

In the end, the two packages will bring down these packages

  1. Ninject
  2. Ninject.Web.WebApi
  3. Ninject.Web.Common
  4. Ninject.Web.Common.WebHost
  5. WebActivatorEx (Sometimes, you have to download it manually)

Now it is very important. For some unknown reasons, NinjectWebCommon.cs was NOT created by the packages. So manually create one, and copy the following content.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourNameSpace.APIs.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YourNameSpace.APIs.NinjectWebCommon), "Stop")]

namespace YourNameSpace.APIs.App_Start
{
 using System;
 using System.Web;

 using Microsoft.Web.Infrastructure.DynamicModuleHelper;

 using Ninject;
 using Ninject.Web.Common; 
 using System.Web.Http;
 using Ninject.Web.Common.WebHost;
 using Ninject.Web.WebApi;


 public static class NinjectWebCommon 
 {
   private static readonly Bootstrapper bootstrapper = new Bootstrapper();

 /// <summary>
 /// Starts the application
 /// </summary>
 public static void Start() 
 {
   DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
   DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
   bootstrapper.Initialize(CreateKernel);
 }
 
 /// <summary>
 /// Stops the application.
 /// </summary>
 public static void Stop()
 {
   bootstrapper.ShutDown();
 }
 
 /// <summary>
 /// Creates the kernel that will manage your application.
 /// </summary>
 /// <returns>The created kernel.</returns>
 private static IKernel CreateKernel()
 {
 var kernel = new StandardKernel();
 try
 {
   kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
   kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

   GlobalConfiguration.Configuration.DependencyResolver = 
     new NinjectDependencyResolver(kernel);
   RegisterServices(kernel);
   return kernel;
 }
 catch
 {
   kernel.Dispose();
   throw;
 }
 }

 /// <summary>
 /// Load your modules or register your services here!
 /// </summary>
 /// <param name="kernel">The kernel.</param>
 private static void RegisterServices(IKernel kernel)
 {
   kernel.Bind<IYourInterface>().To<YourImplementation>();
 } 
 }
}

 

 

Advertisements