First off I create a ControllerFactory for StrucutureMap
public class StructureMapControllerFactory : DefaultControllerFactory { public IContainer Container { get; set; } public StructureMapControllerFactory() { Container = ObjectFactory.Container; } protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { IController controller; if (controllerType == null) { throw new HttpException(404, String.Format(Resources.ControllerNotFound, requestContext.HttpContext.Request.Path)); } if (!typeof(IController).IsAssignableFrom((controllerType))) { throw new ArgumentException(string.Format(Resources.NotAController, controllerType.Name),"controllerType"); } try { controller = Container.GetInstance(controllerType) as Controller; } catch (Exception ex) { throw new InvalidOperationException(string.Format(Resources.UnableToResolveController, controllerType.Name),ex); } return controller; } }
Then in the Global.asax Application_Start method.
Add the setup for StructureMap, I tend to do all that in a separate class:
DependencyInjection.StructureMap.Initialise();
And then set the ControllerFactory to your new custom factory:
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());