Skip to content

Setting up an MVC3 application

Drew Anderson edited this page Jul 11, 2017 · 26 revisions

There are two ways to setup an MVC3 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 Github can also be used for the NuGet package.

Using Binaries from Github

Create a new MVC application and add references to Ninject, Ninject.Web.Common and Ninject.Web.Mvc3 from the Github 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.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();
       RegisterServices(kernel);
       return kernel;
   }

   /// <summary>
   /// Load your modules or register your services here!
   /// </summary>
   /// <param name="kernel">The kernel.</param>
   private void RegisterServices(IKernel kernel)
   {
       // e.g. kernel.Load(Assembly.GetExecutingAssembly());
   }
 
   protected override void OnApplicationStarted()
   {
       base.OnApplicationStarted();
 
       AreaRegistration.RegisterAllAreas();
       RegisterGlobalFilters(GlobalFilters.Filters);
       RegisterRoutes(RouteTable.Routes);
   }
}

NuGet Package

After creating a new MVC3 application run Install-Package Ninject.MVC3 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();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
        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();
        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        // e.g. kernel.Load(Assembly.GetExecutingAssembly());
    }   
}

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

NOTE: If you're using VB.NET to develop an MVC3 application then there are few additional steps to make everything work as expected:

  • In App_Start: rename NinjectMVC3.cs to NinjectMVC3.vb
  • Replace contents of NinjectMVC3.vb with contents provided in this gist: https://gist.github.com/923618

What's the difference between these approaches?

Both approaches exactly do the same. They hook Ninject into MVC applications. The only difference is that they use a different approach to do this. The reason for using different approaches 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.

Upgrading from 2.2 to 3.0

Since Ninject.MVC3 3.0, the extension depends on Ninject.Web.Common. Due to this change the App_Start file was renamed from NinjectMVC3.cs to NinjectWebCommon.cs. You have to merge all your setup code to this new file and delete Ninject.MVC3.cs afterwards.

A second change is that InRequestScope has been removed from Ninject core. This scope is now provided by an extension method in the Ninject.Web.Common extension. It requires that you add using Ninject.Web.Common wherever you want to use InRequestScope.

NinjectHttpApplication has been moved to the namespace Ninject.Web.Common. You have to adjust your usings.