»
S
I
D
E
B
A
R
«
Using StructureMap to Build Your MVC Controllers
July 26th, 2009 by Josh Rivers

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 StructureMap
is 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 the
popular IoC frameworks work in your project. Unfortunately IoC frameworks update a
lot, and the MvcContrib project was finding it pretty hard to keep up with the latest
versions 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 IController
CreateController(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

ConfigureIoC();

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


Leave a Reply

»  Substance: WordPress   »  Style: Ahren Ahimsa