Friday 25 January 2013

MVC4 StrucutureMap ControllerFactory

I am not sure if this is new to MVC4 only, but it does appear that Dependency Injection with MVC just got easier. This code is borrowed, and referenced here so I don't have to keep going off and finding it.

First off I create a ControllerFactory for StrucutureMap

public class StructureMapControllerFactory : DefaultControllerFactory
{
    public IContainer Container { getset; }
    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());