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

2.3k views Asked by At

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?

2

There are 2 answers

0
Remo Gloor On BEST ANSWER

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/

0
carlsb3rg On

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: