title: How to use StructureMap to inject repository classes to the controller?
body: <p>In the current application I am working on I have a custom ControllerFactory class that create a controller and automatically sets the Elmah ErrorHandler.</p>
  
  <pre><code>public class BaseControllerFactory : DefaultControllerFactory
  {
      public override IController CreateController( RequestContext requestContext, string controllerName ) {
          var controller = base.CreateController( requestContext, controllerName );
          var c = controller as Controller;
          if ( c != null ) {
              c.ActionInvoker = new ErrorHandlingActionInvoker( new HandleErrorWithElmahAttribute() );
          }
          return controller;
      }
  
      protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType ) {
          try {
              if ( ( requestContext == null ) || ( controllerType == null ) )
                  return base.GetControllerInstance( requestContext, controllerType );
  
              return (Controller)ObjectFactory.GetInstance( controllerType );
          }
          catch ( StructureMapException ) {
              System.Diagnostics.Debug.WriteLine( ObjectFactory.WhatDoIHave() );
              throw new Exception( ObjectFactory.WhatDoIHave() );
          }
      }
  }
  </code></pre>
  
  <p>I would like to use StructureMap to inject some code in my controllers. For example I would like to automatically inject repository classes in them. </p>
  
  <p>I have already created my repository classes and also I have added a constructor to the controller that receive the repository class</p>
  
  <pre><code>public FirmController( IContactRepository contactRepository ) {
      _contactRepository = contactRepository;
  }
  </code></pre>
  
  <p>I have then registered the type within StructureMap</p>
  
  <pre><code>ObjectFactory.Initialize( x =&gt; {
      x.For&lt;IContactRepository&gt;().Use&lt;MyContactRepository&gt;();
  });
  </code></pre>
  
  <p>How should I change the code in the CreateController method to have the <code>IContactRepository</code> concrete class injected in the <code>FirmController</code>? </p>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>I have changed the BaseControllerFactory to use Structuremap. But I get an exception on the line</p>
  
  <pre><code>return (Controller)ObjectFactory.GetInstance( controllerType );
  </code></pre>
  
  <p>Any hint?</p>