joshcomley
joshcomley

Reputation: 28838

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

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?

Upvotes: 5

Views: 2696

Answers (4)

J.R. Garcia
J.R. Garcia

Reputation: 639

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.

Upvotes: 2

Dale Ragan
Dale Ragan

Reputation: 18270

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

Upvotes: 2

Peter Meyer
Peter Meyer

Reputation: 26061

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!

Upvotes: 5

Talljoe
Talljoe

Reputation: 14827

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();
);

Upvotes: 0

Related Questions