Where to get Ninject 2

Ninject v2 has not been released yet: the sample on this post is based on the official beta released by Nate, but if you want you can download the latest source code directly from the repository online:

The HomeController

What the controller does is just calling the service and putting the greeting returned inside the view model. Also the action is decorated with an ActionFilter that sets the title of the page, always retrieving it from the same greeting service.

All the initialization code of the web application, the one that would normally go into the Application_Start method, now has to go into the OnApplicationStarted one. Inside this method goes the setup of the routing table and the call to the method that registers all the controllers of the application.

RegisterAllControllersIn(Assembly.GetExecutingAssembly());

This method scans all the types inside the assembly supplied, and registers for injection all the controllers it finds.

The Ninject Application class also makes easier creating and configuring the kernel, through the CreateKernel method.

And what about the ActionFilters?

You might wonder where all the configuration needed for injecting dependencies inside action filter went. The cool thing about Ninject 2 is that this kind of injection comes out of the box with the ASP.NET MVC extension. So the only line of code needed it the [Inject] attribute applied to the property of the action filter that will hold the injected dependency. Cool, isn’t it?

What’s next

Ninject v2 is looking very stable, and I’ve used it in production code, and didn’t give me any problem, so I really encourage you download the latest bits, and play around with it.

If you want to try this by yourself, I packaged the sample into a VisualStudio 2008 solution that you can download

Comments on this entry:

I switched from Ninject 1.0 to 2.0 in a web project and each page processing time went from 20ms to 60ms. Have you experienced anything similar? I'm wondering if that's expected or if I'm doing something wrong.

I was using StructureMap in my recent project. I really liked it's "feature" to cache object for the duration of http context during registration, like:ForRequestedType().CacheBy(InstanceScope.HttpContext);That was really helpful, and easy. How can I "copy" this feature to using Ninject lib? Can I use Ninject in medium trusted environment? There are some problems with StructureMap - (it's calls to some reflection methods).

does not work for me:I have a very simple controller with an action "Index" with a nullable id parameter. When the application gets loaded with the defaults, ok, the id is null, but when I call (from action links or from browser address bar either) e.g. http://localhost:/controller/index/3 the id parameter never assumes the value 3. What's wrong?thanks