title: Custom Controller Factory, Dependency Injection / Structuremap problems with ASP.NET MVC
body: <p>I recently tried to implement dependency injection using StructureMap. I managed to follow the example all the way but I'm encountering a thrown exception every time I try to run the application. Here's some code snippets from my controller factory.</p>
  
  <pre><code>public class StructureMapControllerFactory : DefaultControllerFactory
  {
      protected override IController GetControllerInstance(Type controllerType)
      {
          if (controllerType == null)
              throw new ArgumentNullException("controllerType");
  
          return ObjectFactory.GetInstance(controllerType) as Controller;
      }
  }
  </code></pre>
  
  <p>My Global.asax calls a static BootStrapper class which registers all my dependencies but it looks like the StructureMapControllerFactory's GetControllerInstance is getting called twice. The first time it's called, a proper controllerType is passed in but it's always null on the second calling.</p>
  
  <p>The first time GetControllerInstance is called, the type is set to HomeController which is correct. The code the fires in HomeController and it returns the View(). On the return of the View(), the Page_Load event is called on the aspx file. After stepping through that, it arrives at a line:</p>
  
  <p>httpHandler.ProcessRequest(HttpContext.Current);</p>
  
  <p>That's where the GetControllerInstance is called the second time.</p>
  
  <p>Here's my Global.asax bits which may be relevant:</p>
  
  <pre><code>   protected void Application_Start()
      {
          RegisterRoutes(RouteTable.Routes);
  
          Bootstrapper.ConfigureStructureMap();
  
          ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
      }
  </code></pre>
  
  <p>I'm very keen to get dependency injection working and would be most appreciative if anyone can help me out. :)</p>