Getting started with Ninject

前端 未结 3 2003
傲寒
傲寒 2020-12-29 14:37

I watched the first 2 beginner tutorials for Ninject on dimecasts.net. Now, I want to use Ninject 2.2 in ASP.NET MVC 3. I want a view with a mocked out Model. I get objec

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 14:45

    There is an issue with your controller class, the constructor with the dependency is private. Your controller should look like:

    public class HomeController : Controller
    {
        private readonly IMilestoneService _service;
    
        public HomeController(IMilestoneService service)
        {
            _service = service;
        }
    
    }
    

    Don't even include a public parameterless constructor, it isn't even valid, your class needs that dependency to function.

    In fact, I also insert a null check against that dependency in the constructor just to be sure my class is valid on construction:

    public class HomeController : Controller
    {
        private readonly IMilestoneService _service;
    
        public HomeController(IMilestoneService service)
        {
            _service = service;
            Enforce.NotNull(() => _service); // lambda to auto-magically get variable name for exception
        }
    
    }
    

    There also may be an issue with your MvcApplication class.

    Instead of protected void Application_Start(), there is a different function you can override, protected override void OnApplicationStarted()

    This is where your calls to setup routing should go:

    public class MvcApplication : NinjectHttpApplication
    {
    
        public override void Init()
        {
            base.Init();
            Mappers.Initialize();
        }
    
        protected override Ninject.IKernel CreateKernel()
        {
            return Ioc.Initialize();
        }
    
        protected override void OnApplicationStarted()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }
    
        public static void RegisterRoutes(RouteCollection routes) 
        {
            Routing.RegisterRoutes(routes);
            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
        }
    }
    

    Of course, if you are already calling Application_Start that's fine too, but I didn't see it in the OP.

提交回复
热议问题