Using StructureMap to Build Your MVC Controllers

The simplest things seem to be the hardest to find the up-to-date documentation on.Adding a ControllerFactory to MVC is very simple, and making it work with StructureMapis pretty quick, but do you really want to write any of that code? Of course not.Somebody else can do it.

The MVC Contrib project has built all of the code you need to make a number of thepopular IoC frameworks work in your project. Unfortunately IoC frameworks update alot, and the MvcContrib project was finding it pretty hard to keep up with the latestversions when they compiled their builds. So that code is deprecated. Don’t use it.

Here’s how you add StructureMap to build controllers in your MVC project:

Create a StructureMapControllerFactory Class

using System;using System.Web.Mvc;using System.Web.Routing;using StructureMap;namespace MvcContrib.StructureMap{public class StructureMapControllerFactory: DefaultControllerFactory{public override IControllerCreateController(RequestContext context, string controllerName){Type controllerType = base.GetControllerType(controllerName);return ObjectFactory.GetInstance(controllerType) as IController;}}}

Add a Method to Global.asax

private void ConfigureIoC(){ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());}

Add a call to that method in Application_Start


….and now we can go out for steak and exotic dancers. Your controllers will have theirdependencies injected all nice and purty.