7.3. Solution

There are several IoC Containers out there that we can choose from. There are also several online articles and resources comparing the pros and cons of each container. Most of the popular containers are very comparable in features, and your decision might come down to style. I personally like Ninject (www.ninject.org) for its ease of use, fluent interface, light weight, and good online and community support.

The first thing to do is download Ninject and reference the Ninject.core.dll and Ninject.Framework.Mvc.dll assemblies in the web project. Next, we change the Global.asax file so that the MvcApplication class inherits from NinjectHttpApplication instead of System.Web.HttpApplication. NinjectHttpApplication is an abstract class that will replace the default controller factory with a Ninject-aware factory that will handle the injection of controllers. There are two virtual methods that we have to override, RegisterRoutes and CreateKernel. The final class looks like this:

public class MvcApplication : 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
    );
} private StandardKernel _kernel; protected override IKernel CreateKernel() { IModule[] modules = new IModule[] { new AutoControllerModule( Assembly.GetExecutingAssembly()), ...

Get ASP.NET MVC 1.0 Test Driven Development: Problem - Design - Solution now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.