How Do I Use StructureMap with ASP.NET MVC 3

Update: If you want to use StructureMap with ASP.NET MVC 5, I have a walkthrough on this now as well.

As I write this, the best resource for official documentation on ASP.NET MVC 3 is of course MSDN. You can also learn more about ASP.NET MVC 3 here. However, neither of those mention how to properly set up an IOC Container (like StructureMap) with ASP.NET MVC 3. After some searching, I was able to get things working using the RTM version of ASP.NET MVC 3. Here’s what I had to do.

Step One – Global.asax – Application_Start()

First, you need to wire things up when your application starts. You can put all of your container registration stuff right into your Global.asax, but that violates SRP. I typically have a separate project in my solution devoted to DependencyResolution and this project exposes an EnsureDependenciesRegistered() method that makes sure all of my types are wired up. This project handles everything below the UI level, so any UI-specific wireup that is needed (like, say, MVC ControllerActivators) needs to still happen within the UI project, so I do end up with one line of configuration in my Global.asax. Here are the two methods involved:

 

Step Two – StructureMapDependencyResolver implementation of IDependencyResolver

You need one of these. You can cut and paste this one, or you might find one already in a project like MVCContrib.

 

Update: Thanks to Jeremy’s comment below and some emails exchanged with K. Scott Allen, I’ve updated the above code to streamline it and also removed the implementation of IControllerActivator, which is not needed here. One thing that bugs me when I grab code from the internet is when it doesn’t work because I don’t have the right using statements or references. To avoid this issue, here are my using statements for the above code to work:

 
The one last bit that you are likely missing is the static method for IoC.GetContainer(). I have a static helper class called IoC that handles all of my dependency resolution in a container-agnostic manner. In the above code the only thing I’m using it for is to get an instance of my container, which you can easily do using whatever technique you like (you may just new it up in your InitializeContainer() method). I also found this article on Dependency Injection in MVC 3 with Unity to be helpful.

  • Jeremy D. Miller

    Ugh, you gotta watch out for this one:

    public object GetService(Type serviceType)

    {

    return _container.TryGetInstance(serviceType);

    }

    MVC3 is apparently assuming that the underlying container will build a concrete "serviceType" if it can. StructureMap’s TryGetInstance() is specifically meant to "return ‘serviceType’ *only* if it is explicitly configured.

    You probably need to check if the result is of TryGetInstance(type) is null, then if serviceType is concrete, turn around and do:

    container.GetInstance(serviceType)

    Ugly workaround, but such is life. This’ll show up on my blog soon.

  • Damon Stephenson

    Thanks for the tip Jeremy. I had my DependencyResolver that way.

  • Twitter Trackbacks for Updated: MVC 3 and StructureMap for DI – [stevesmithblog.com] on Topsy.com

    Pingback from Twitter Trackbacks for Updated: MVC 3 and StructureMap for DI – [stevesmithblog.com] on Topsy.com

  • mick delaney

    how do we wire up child/nested containers per request in SM + MC3???

  • Improving ASP.NET MVC Application Performance at MVCConf

    Yesterday I gave a presentation to a little over 300 attendees of MVCConf on Improving ASP.NET MVC Application Performance.  There were some great responses on twitter and generally the ratings on SpeakerRate were positive, which was great because

  • Introducing the CachedRepository Pattern

    In this first part of a series on adding support for caching to the Repository Pattern, I’d like to show how to very simply control whether or not caching is performed on a per-repository basis through the use of an Inversion of Control Container . 

  • Thomas Levesque

    I think the code for GetServices is incorrect… It will never anything if serviceType is an interface or abstract class, because GetType always return the concrete type, so the predicate in Where will always be false.

    This should work better:

    public IEnumerable<object> GetServices(Type serviceType)

    {

    return _container.GetAllInstances<object>()

    .Where(s => serviceType.IsAssignableFrom(s.GetType()));

    }

  • Matt Hinze

    GetServices might be better implemented as return _container.GetAllInstances(serviceType).Cast<object>();

    https://groups.google.com/forum/#!topic/structuremap-users/HvLIy7Bbbtg for more info

  • Jesse

    your post does not properly show how to set up an Ioc Container such as StructureMap with ASP.Net MVC either.

    I created a reference to StructureMap in my project and used your code and there are a few things obviously missing.

    You stated "I typically have a separate project in my solution devoted to DependencyResolution" but failed to elaborate on what is going on in that other project in order for StructureMap to work.

  • ssmith

    @Jesse,

    You’re right, I did make some basic assumptions, and I apologize. You should add a reference to StructureMap to your MVC projet in order to use the code above. Also, I left out my DependencyResolution project to keep things simple, since it’s certainly not required that you do things that way in order to use SM. I’ll try and write a post soon that shows how I structure my solution, including the DependencyResolution project.

  • Jesse

    Unfortunately or fortunately depending on your perspective, us newbs depend on blogs such as yours to learn this stuff so assumptions kind of leave us hanging. Prior to visiting your blog last night I failed miserably at getting the latest MVC 3 ninject up and running, so structuremap was my next choice.

  • ssmith

    It’s good feedback and I’ll try and make sure to give you everything you need in the future, and update this article next chance I get to include it all. Really the easiest way to get going with SM today is to use the NuGet package for StructureMap. You can learn more about Nuget at http://nuget.codeplex.com.

  • Jesse

    Thanks, I did use the nuget package and it did provide a bit of a head start.

  • dotnetguy

    Problem with this line

    var container = (IContainer)IoC.GetContainer();

    IoC is unknown / does not exist. please advise

    Thanks.

  • ssmith

    @dotnetguy,

    That’s just my wrapper for my IOC container. If you’re using StructureMap directly, you would just replace that with something like

    new Container();

  • Madison

    Hi Steve,

    I hope you can help.

    I’ve been reading your information at the suggestion of Jon Galloway, and trying to implement your StructureMap solution but I must be getting something twisted.

    Between your fork at the MVCMusicStore and some of your blog posts I see some info on modifying global.asax but there is an app_start file from the StructureMap install. I have left the file in place and not changed global but I keep getting the following error when running the app.

    No parameterless constructor defined for this object.

    Any ideas?

    Thanks

  • Steve Smith

    @Madison,

    The App_Start stuff is probably coming from a NuGet installation of SM. Have you tried using Nuget to install StructureMap for MVC3? It’s going to be the simplest way to get you up and running. You can search at nuget.org to find the correct package.

  • DDD: 2- Framework de IoC (Service Pack 1)

    Después de la última sacudida recibida por la encapsulación del Container que hicimos en el artículo