Skip to content

Setting up an mvc webapi application

remogloor edited this page Mar 30, 2012 · 13 revisions

There are two ways to setup an MVC WebAPI application. The first one in to use the binaries from the Github download. The second one to install the nuget package. Both ways are installing the same assemblies. The approach described in using binaries from Google Code can also be used for the NuGet package.

Using Binaries from Google Code

Create a new MVC WebAPI application and add references to Ninject, Ninject.Web.Common and Ninject.Web.WebApi from the Google Code download. Then change the global.asax to derive from NinjectHttpApplication instead of HttpApplication and override CreateKernel to create a kernel and load all modules that you need in your application. One way to load all modules is to tell Ninject to load all modules from your application assemblies. Here is an example of the global.asax.

public class MvcApplication : NinjectHttpApplication
{
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
   {
       filters.Add(new HandleErrorAttribute());
   }
 
   public static void RegisterRoutes(RouteCollection routes)
   {
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
       routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional });

       routes.MapRoute(
           "Default", // Route name
           "{controller}/{action}/{id}", // URL with parameters
           new
           {
               controller = "Home",
               action = "Index",
               id = UrlParameter.Optional
           });
   }
 
   protected override IKernel CreateKernel()
   {
       var kernel = new StandardKernel();
       kernel.Load(Assembly.GetExecutingAssembly());
       return kernel;
   }
 
   protected override void OnApplicationStarted()
   {
       base.OnApplicationStarted();
 
       AreaRegistration.RegisterAllAreas();
       RegisterGlobalFilters(GlobalFilters.Filters);
       RegisterRoutes(RouteTable.Routes);
   }
}

NuGet Package

After creating a new MVC3 WebAPI application run Install-Package Ninject.Web.WebApi from the package manager console. Make sure that you are using NuGet 1.6 or higher. Using an older version will result in missing references. This will download and install all required assemblies and add some source code to integrate it into the application. After the installation you will find the NinjectWebCommon class shown below in the App_Start folder.

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

    /// 
    /// Starts the application
    /// 
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }
	
    /// 
    /// Stops the application.
    /// 
    public static void Stop()
    {			
        bootstrapper.ShutDown();
    }
		
    /// 
    /// Creates the kernel that will manage your application.
    /// 
    /// The created kernel.
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        return kernel;
    }

    /// 
    /// Load your modules or register your services here!
    /// 
    /// The kernel.
    private static void RegisterServices(IKernel kernel)
    {
    }		
}

Modify the CreateKernel method to create the kernel as you need it in your application. For almost all application no change will be necessary here. Now load your modules or define bindings in RegisterServices method.

What's the difference between these approches?

Both approaches exactly do the same. They hook Ninject into MVC WebAPI applications. The only difference is that they use a different approch to do this. The reason for using different approchaches is that the NuGet package can provide out of the box integration by adding one file. Otherwise it would require complicated modifications of the global.asax

NOTE: If you decide to go with the first approach if using the NuGet package (for which there is no reason) you have to delete the App_Start folder and remove the references to WebActivator and Microsoft.Web.Infrastructure.