What's the proper way to configure Ninject for an MVC3 application?

牧云@^-^@ 提交于 2019-12-12 10:43:43

问题


I've read several articles regarding the setup of Ninject for MVC3 projects.

Some say that your Global.asax.cs should inherit from NinjectHttpApplication, others register modules when constructing the StandardKernel via Application_Start().

I personally used NuGet and it went a different way creating a AppStart_NinjectMVC3 class, and starting it up using

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart_NinjectMVC3), "Start")]

Are there any advantages/disadvantages to each?


回答1:


Ian and I have been quite busy regarding this topic during the last few days. Ninject.Web.Mvc and Ninject.MVC3 have been merged. There are still the two ways to either derive from NinjectHttpApplication or to install the nuget package. But now they are based on the same code so that they have the same features. See my blogpost about more details:

http://www.planetgeek.ch/2011/02/22/ninject-mvc3-and-ninject-web-mvc3-merged-to-one-package/




回答2:


I was looking for an answer to the same question, but seem to have found a decent answer myself. And btw: I'm an MVC, Ninject, DI n00b so feel free to shoot me if I'm way off here, but I think I've got it pretty much figured out.

The "PreApplicationStartMethod" attribute already exists in System.Web and can be used to run methods even before Application_Start(). That means it's very good for DI stuff, since you might need to start injecting in Application_Start() already, and by using the PreApplicationStartMethod you can keep the injection stuff out of your Application_Start() and make sure it's the very first thing to start when your application starts.

The problem is that Microsoft only allows 1 method to be marked with this attribute, something they admit was a design flaw. That's why they have created the WebActivator class to circumvent this short-coming.

One of the perks of allowing multiple methods to be marked as PreApplicationStartMethod's is that NuGet packages that require initialization can be inserted into your application without touching the existing code, simply by marking some kind of initialization method with the WebActivator version of the PreApplicationStartMethod attribute.

This method is pretty much the same as just building your kernel in Application_Start(), but the Ninject stuff kicks in earlier.

By overriding NinjectHttpApplication, you get Ninject to do a lot of common MVC-related binding jobs for you, like binding HttpContext etc. With the WebActivavtor/Application_Start() method you have to do this yourself as far as I can tell.

Some good links:

  • MSDN
  • ILearnable
  • Ninject.Mvc@github


来源:https://stackoverflow.com/questions/5064766/whats-the-proper-way-to-configure-ninject-for-an-mvc3-application

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