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

2

6

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?

Leddy answered 21/2, 2011 at 10:23 Comment(0)
M
6

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/

Maxinemaxiskirt answered 22/2, 2011 at 21:4 Comment(0)
F
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:

Fini answered 22/2, 2011 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.