Ninject: Killer IoC

In my previous post, The Best IoC Container, I decided to go with StructureMap as the framework of choice.  I received a comment telling me to check out Ninject and then a day or two after, I saw Corey Gaudin’s post on using Ninject with MVC, so I decided to try it out.

It wasn’t too hard to get up and running in asp.net mvc.  Corey’s post was a good starting point but I was too lazy to type all his code in, I wrote my own.  It was pretty easy to get Ninject to work.

I basically created a NinjecteControllerFactory class that inherits from the DefaultControllerFactory and overrode a couple of methods.  The class looks like this:

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel _kernel;
    public NinjectControllerFactory(params IModule[] modules)
    {
        _kernel = new StandardKernel(modules);
    }

    protected override IController GetControllerInstance(Type controllerType)
    {
        return _kernel.Get(controllerType) as IController;
    }
}

 

Then in my Gloval.asax.cs file, I called this code to setup Ninject.

IModule[] modules = new IModule[] { new WebModule() };
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(modules));

 

The WebModule module has my configuration and looks like this:

public class WebModule : StandardModule
{
    public override void Load()
    {
        Bind<IAppService>().To<AspAppService>();
        Bind<IEmailService>().To<EmailService>();
        Bind<IContactService>().To<ContactService>();
        Bind<IContactRepository>().To<SqlContactRepository>();
        Bind<IFormsAuthentication>().To<FormsAuthenticationWrapper>();
        Bind<MembershipProvider>().ToConstant(Membership.Provider);
    }
}

 

Of course, you can create as many modules as you want to configure your application and pass them in the controller Factory.

This code was working fine for me and then Nate Kohari mentioned that there is a Ninject.Framework.Mvc extension that allows me to easily integrate Ninject into the MVC pipeline.  So, I decided to download the code, build it and use it.  I initially had some issues because it was referencing a different version of the core dll, so I had to rebuild that as well.

I changed my Global.asax.cs file to the following:

public class GlobalApplication : NinjectHttpApplication
{
    protected override void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
    }

    protected override IKernel CreateKernel()
    {
        IModule[] modules = new IModule[] { new AutoControllerModule(Assembly.GetExecutingAssembly()), new WebModule() };
        return new StandardKernel(modules);
    }
}

Initially I was getting errors when navigating to an injected controller, which was fixed by add the AutoControllerModule to my modules and passing it the current assembly.

So far Ninject is looking great, the API is fluent and very discoverable and the contextual binding is very slick.  So I am going to stick with it for now and see how it goes.  The documentation seems pretty good and the Nate is very responsive in the Google Group.

The Best IoC Container?

As I previously mentioned in my post “The Best JavaScript Library“, I am in the process of developing an application/writing a book.  I will be using asp.net MVC and a TDD approach to the application and book.  As I have done with the JavaScript framework selection, I decided to look around and evaluate/review my options for an Inversion of Control (IoC) Container.

Naturally, my research lead me to a post by Scott Hanselman (see it here) which lists some of the more popular IoC and dependency injection frameworks out there.

Spring.Net

I started of looking at Spring.Net and was very impressed by its features, samples/tutorials and documentation but it felt like it would be too much for this project and the learning curve seemed somewhat steep.  Its configuration syntax also looked very verbose.  But if you want to learn more there is a good article over here.

Castle Windsor

It looked easier to learn/use than spring.net but there getting started section was incomplete even though Scott says that it is well documented.  So that was a little discouraging.

Autofac

I really liked there syntax and looked really easy to use and figure out, but the documentation was very limited.  It was just a bunch of wiki pages in Google Code.  Though, they did have instructions on how to integrate it with MVC

StructureMap

Initially, I learned about structure map from a post by Phil Haack’s and I kind of liked it right away.  It was easy to pick up and figure out and Phil’s example helped to get me started quickly.  I checked there website and it has an impressive list of features and is well documented.

PostSharp

PostSharp is really cool but is not an IoC container.  It is a policy injector and a really easy way to do Aspect Oriented Programming (AOP).  Rather than trying to explain what exactly it does and screw it up, take a look at the “About PostSharp” page.  Even better check out this “getting started” walkthrough – you will be very impressed.

Must Pick One

I know there is a lot more IoC containers out there (which I glanced over), but these were sufficient for me.  Initially, I thought about using AutoFac but when I started to actually use it and ran into some issues, the documentation was not helpful at all.

I have decided to go with StructureMap as my IoC Container and dependency injector.  I might also use PostSharp to implement logging and tracing as aspects – there is no cleaner way.

Helpful Links

For a good explanation of IoC Containers and the Dependency Injection patter, read this article by Martin Fowler.

This also a good explanation that might help you understand IoC Containers.

You should definilty take a look Matthew Podwysocki’s comparison of the different IoC containers out there and their different (or rather similar) configuration and syntax.

Books you must Read

Applying Domain-Driven Design and Patterns

And Martin Fowler’s indispensable reference for software patterns Patterns of Enterprise Application Architecture

Validate my Choice

What do you think of my choice?  Does it really matter which one I go with?  Do you prefer a different IoC container and why?

Time to choose a unit testing framework… I love choices!!!

[poll id="3"]