Search code examples
asp.net-mvc-5ninject.web.mvc

NinjectWebCommon doesn't load NinjectModule from other assemblies


I am trying to load dependencies using Ninject. But NinjectWebCommon is unable to load NinjectModules in the referred assemblies.

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

            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)
    {
    }
}

below is the module I am trying to load

using System;
using Ninject.Modules;

namespace App.Security
{
    public class SecurityModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IAppAuthenticationManager>().To<AppAuthenticationManager>();
            Bind(typeof(IAppUserManager<>)).To(typeof(AppUserManager<>));
            Bind<AppUser>().ToSelf();
        }
    }
}

I am unable to figure out why it can't load the module?


Solution

  • After some head banging session, I figured out that I need to call

    kernel.Load<SecurityModule>();
    

    in the RegisterServices method of NinjectWebCommon.