Configuring MVC 4 with StructureMap

I started a new MVC4 project and wanted to use StructureMap for my IOC container of choice. I followed Phil’s post about wiring up dependency resolvers in mvc 4, but I kept getting the following error: “StructureMapDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.
Parameter name: commonServiceLocator”

Took a little digging, but I found the CommonServiceLocator project from the Microsoft Patterns and Practice group.  That project has a StructureMap implementation of the IServiceLocator interface for StructureMap.  After I installed the CommonServiceLocator nuget, I was able to reference IServiceLocator in my code.   Taking the code from the CommonServiceLocator implementation, I ended up with the following:

The following code will setup mvc to use structuremap as the dependency resolver. Add the webactivator nuget and toss the following file in your app_start folder:

using System.Web.Mvc;
using MvcKickstart.Infrastructure;
using StructureMap;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourProject.IocConfig), "PreStart", Order = -100)]

// This gets installed automatically with the MvcKickstart nuget (https://nuget.org/packages/mvckickstart)
namespace YourProject 
{
  public static class IocConfig
	{
		public static void PreStart() 
		{
			// If changes need to be made to IocRegistry, please subclass it and replace the following line
			ObjectFactory.Initialize(x => x.AddRegistry(new IocRegistry(typeof(IocConfig).Assembly)));
			DependencyResolver.SetResolver(new StructureMapDependencyScope(ObjectFactory.Container));
		}
	}
}

Hope this helps someone looking to do the same!

5 thoughts on “Configuring MVC 4 with StructureMap

  1. Your .Cast() extension method isn’t included here, or its namespace isn’t if it’s a built-in method.

    Is there a working MVC4RC project you can point to that shows everything wired up, perhaps on Github?

  2. And … of course you would also need the following line in global.cs : )

    GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(ObjectFactory.Container);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>