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.

Advertisements

0 thoughts on “Ninject: Killer IoC

  1. Pingback: ASP.NET MVC Archived Blog Posts, Page 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s