Does anyone know of a good guide to get Ninject 2 working in ASP.NET MVC?

邮差的信 提交于 2020-01-10 19:51:37

问题


I'm struggling with the documentation to figure out exactly what I need to. The documentation (to my understanding) is for 1.5 anyway.

N.B: I don't want to extend NinjectHttpApplication

I've configured it to use the NinejctControllerFactory in Application_Start() but I get a null reference exception on the KernelContainer.Kernel when it tries to create a controller. Where do I configure the Kernel if I'm not extending NinjectHttpApplication?


回答1:


Take a look at this blog post. It should help clarify the process you need to perform on how to configure the kernel.

http://www.kevinrohrbaugh.com/blog/2009/8/7/using-ninject-2-with-aspnet-mvc.html




回答2:


Since you're already extending another HttpApplication-derived class, my thoughts are to just copy the relevant source code from the NinjectHttpApplication class into your extended HttpApplication class. Rather than cut and paste it, just look at the source for NinjectHttpApplication in the Ninject2 Ninject.Web.Mvc extension project here.

I would specifically copy the stuff in Application_Start() and Application_Stop() methods. The other methods for registering controllers are nice, but you can register your controllers however you wish. You'll note in the Application_Start(), the kernel is created by calling the pure virtual function CreateKernel() -- you can simply create your kernel inline right there. Additionally, note the presence of the Kernel property on the NinjectHttpApplication class -- I'd copy that into your own class as well. It would appear the intent here is that the HttpApplication-derived class effectively serves as the KernelContainer.

Disclaimer: I haven't tried this to see if it works, though I will be shortly. I've used Ninject 1.x in a web project and intend to upgrade to Ninject 2 in the near future; however, I'll probably be able to derive directly from NinjectHtppApplication. Good luck!




回答3:


Not being able to derive from NinjectHttpApplication isn't a big deal. It's not doing too much, it's very convenient though. Peter Meyer's suggestion is the way to go. Just check out the source here. You will have to inherit from IHaveKernel though.




回答4:


You still should paste the code you have so people can see where you might have gone wrong.

I think this code should be placed in your Application_Start:

ControllerBuilder.Current.SetControllerFactory(typeof(NinjectControllerFactory));
KernelContainer.Kernel = new StandardKernel(
    new AutoControllerModule(Assembly.GetExecutingAssembly();
);


来源:https://stackoverflow.com/questions/962690/does-anyone-know-of-a-good-guide-to-get-ninject-2-working-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!