ASP.NET Web API Ninject 3.0 Setup

ASP.NET 4 and Web API Ninject 3.0 SetupThe 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.

Add code to CreateKernal method
1
2
3
4
    GlobalConfiguration.Configuration
        .ServiceResolver
        .SetResolver(t => kernel.TryGet(t),
                     t => kernel.GetAll(t));

Take a look at NinjectWebCommon.cs.

Ninject NuGet package adds:

  • WebActivator.PreApplicationStartMethod and WebActivator.ApplicationShutdownMethodAttribute
  • DynamicModuleUtility module registration
  • Initializes Bootstraping
  • Tears down Bootstraping
  • Configs Ninject Kernal for use with ASP.NET MVC 4
  • Adds RegisterServices to add service bindings

To register Ninject Container with Web API – simply update the CreateKernal method to set Ninject kernal to the Global Configuration Service Resolver.

NinjectWebCommon.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
using System.Web.Http;
//
using yammer.analytics.Infrastruture.Logging;

[assembly: WebActivator.PreApplicationStartMethod(typeof(yammer.analytics.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(yammer.analytics.App_Start.NinjectWebCommon), "Stop")]

namespace yammer.analytics.App_Start
{
    using System;
    using System.Web;
    //
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    //
    using Ninject;
    using Ninject.Web.Common;

    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();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);

            GlobalConfiguration.Configuration
                .ServiceResolver
                .SetResolver(t => kernel.TryGet(t),
                             t => kernel.GetAll(t));

            return kernel;
        }

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

References

Comments