Search code examples
asp.net-mvc-3ninject-2

Ninject multiple modules


I didnt think this would be a problem originally, but as I keep getting exceptions thought I would post here incase im being an idiot...

I have 2 module classes, one sets up NHibernate and one sets up MVC Controllers, now the problem I have is that I have something like below:

public class NHibernateModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISessionManager>().To<SessionManager>();
    }
}

public class ControllerModule : NinjectModule
{
    public override void Load()
    {
        Bind<SomeController>().ToSelf()
                             .WithConstructorArgument("sessionManager", Kernel.Get<ISessionManager>());
    }
}

Whenever I try to use the controller, it just bombs out telling me that its having problems binding the sessionManager argument. I make sure the list has the Nhibernate module in before the Controller module when I create the kernel.

Is there anything immediately stupid in what im doing above?


Solution

  • Assuming:

    public class SomeController : Controller
    {
        private readonly ISessionManager _sessionManager;
        public HomeController(ISessionManager sessionManager)
        {
            _sessionManager = sessionManager;
        }
    
        public ActionResult Index()
        {
            return View();
        }
    }
    

    The following should be sufficient:

    public class NHibernateModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ISessionManager>().To<SessionManager>();
        }
    }
    
    public class ControllerModule : NinjectModule
    {
        public override void Load()
        {
            Bind<SomeController>().ToSelf();
        }
    }
    

    and in 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",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
    
        }
    
        protected override void OnApplicationStarted()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    
        protected override IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
            {
                new NHibernateModule(),
                new ControllerModule()
            };
    
            return new StandardKernel(modules);
        }
    }