ASP.NET MVC 3, IDependencyResolver, and StructureMap

Update: this blog is no longer active. For new posts and RSS subscriptions, please go to

ASP.NET MVC 3 offers new facilities for easy dependency injection in various parts of the application that you might want to implement yourself.  Brad Wilson discusses the new features in an extensive series of posts.  In the Beta version and beyond, the way you do this is by creating a class that implements IDependencyResolver and serves as an adapter to the IoC container of your choice.

I happen to like StructureMap as an IoC container so I thought I ‘d wire it up for use in ASP.NET MVC 3.  IDependencyResolver isn’t exactly a complex interface to implement but being the properly lazy developer that I am I thought I’d look around on the web to see if anyone had already offered up an implementation for StructureMap.  I found a few different blog posts that all had pretty much the same code (such as Brandon Satrom’s) so I grabbed it and dropped it into my application.  I then tried to have one of my controllers pulled from the container and . . . met with utter failure.

Specifically, StructureMap kept insisting that it had no idea what I was talking about when my IDependencyResolver adapter asked for an instance of my TitlesController (i.e. container.TryGetInstance(serviceType) was returning null).  The framework would then fall back to trying to create an instance on its own which would throw an exception because this controller was designed for dependency injection and didn’t have a parameter-less constructor.

This was particularly aggravating because all the implementations I found on the web seemed to be the same and apparently they were working for other people.  I beat my head against this problem for, um, longer than I should have, I guess, until I finally found a email thread started by Jimmy Bogard on the StructureMap users list that clarified the problem for me.  The issue is that while StructureMap’s Container.GetInstance() will create an instance of a concrete type without it being explicitly registered, Container.TryGetInstance() doesn’t do that.  Container.TryGetInstance() will give up and return null if the type you’re asking for isn’t explicitly registered as a plugin type.  Coincidentally, the very first thing I was trying to pull out of the container was a concrete type (my controller class).  The existing implementations will work for registered interfaces but not for controllers which are requested by concrete type.

By the way, while researching all of this I ran across this thread in which Jeremy Miller points out that the original implementation of of IDependencyResolver.GetServices was wrong, too.

So here’s my IDependencyResolver implementation for StructureMap which takes StructureMap’s non-intuitive behavior into account and also tries to minimize the number of exceptions that have to be thrown and handled:

(UPDATE: I removed some registration code from the constructor that was causing confusion and probably wasn’t necessary (at least not for resolving concrete controller types, anyway.)  If you need to resolve interface types, you’ll need to register them with StructureMap in your app’s registration code or maybe do it below in the constructor.)

public class StructureMapDependencyResolver : IDependencyResolver


    readonly IContainer _container;


    public StructureMapDependencyResolver(IContainer container)


        _container = container;


        // TODO: if you haven’t registered necessary interfaces somewhere else, you’ll need to do so here.



    public object GetService(Type serviceType)


        if (serviceType.IsClass)


            return GetConcreteService(serviceType);




            return GetInterfaceService(serviceType);




    private object GetConcreteService(Type serviceType)




            // Can’t use TryGetInstance here because it won’t create concrete types

            return _container.GetInstance(serviceType);


        catch (StructureMapException)


            return null;




    private object GetInterfaceService(Type serviceType)


        return _container.TryGetInstance(serviceType);



    public IEnumerable<object> GetServices(Type serviceType)


        return _container.GetAllInstances(serviceType).Cast<object>();



Comments (11)

  1. Brandon Satrom says:

    Hey Eric,

    Thanks for the link. Sorry to hear that my sample didn't work for you. It's odd, because y.AddAllTypesOf<IController>() in Configure() should explicitly register all controllers in your application by scanning all App base directory assemblies (the line right above adds these), so TryGetInstance shouldn't encounter any problem. Did you try calling container.WhatDoIHave() somewhere after this in debug to inspect the container?

    Happy MVCing!

  2. SaintGimp says:

    @Brandon, I did use WhatDoIHave() and it showed that it had IController as a plugin type and all of my concrete controllers as instances of that type.

    It turns out that y.AddAllTypesOf<IController>() will register IController as a PluginType and will register all of the implementors of IController as instances of that type, as I saw from WhatDoIHave().  The problem is that TryGetInstance *only* considers PluginTypes and returns null if the requested type isn't in that list, whereas GetInstance first looks at PluginTypes and if it doesn't find a match there then it looks at known concrete types and throws only if the requested type is not in either list, so the behaviors are different.

    I'm using StructureMap 2.6.1 here.  Were you able to get something like a concrete controller to be resolved using your sample?  If so, what version of StructureMap were you using?

  3. Jason Querido says:

    Thanks for this post. I've spent so much time trying to get StructureMap to behave in MVC3, all to no avail. I think I've read most of the same posts/threads that you mention here. Unfortunately not even this one worked for me.

    After hours of frustration, I removed all traces of StructureMap from my project and typed "install-package Ninject.MVC3" into NuGet and hit F5. It failed with a very nice error message that reminded me to explicitly define my mappings (I was relying on the conventions, I'll have to look into these for Ninject). After adding the mappings, it ran first try. No hooks in App_Start were even necessary.

    I've always preferred StructureMap, but Ninject has really impressed me here.

  4. Brandon Satrom says:

    @Eric, Yes, I did manage to get all of this working, and had no issue. But something else did just occur to me. Did you create an IControllerFactory or IControllerInvoker? My sample includes both and works with both, though I prefer the IControllerInvoker. If you're not using either, or don't want to use either, my original code wouldn't work at all, and I expect that the code you landed on would be sufficient, and save you another class if you wanted to avoid the Factory or Invoker.

  5. SaintGimp says:

    @Brandon, No, I didn't create an IControllerFactory or IControllerInvoker implementation.  I think that's the point of the new IDependencyResolver interface in MVC3 – you no longer have to create the other classes in order to get your controllers DI'ed.  An implementation of IDependencyResolver is all you need to DI everything in MVC3, assuming of course that the implementation works correctly.  🙂

  6. Brandon Satrom says:

    That, and assuming you don't want finer-grained control over controller invocation, which I typically do. That said, it's good to know of that issue with StructureMap in cases where you forgo the factory or invoker.

  7. Frank says:

    Hoping to get help here.

    In the GetConcreteService (after I hit Ctl-Alt-E and set to get CLR exceptions), I get "StructureMap Exception Code:  202

    No Default Instance defined for PluginFamily System.Web.Mvc.ModelMetadataProvider, System.Web.Mvc, Version=, Culture=neutral,"

    My registration is:

    _container.Configure(x =>

                   x.Scan(s =>



                       s.AddAllTypesOf<IController>().NameBy(c => c.Name.Replace("Controller", "").ToLower());




    On startup, all I have is:

    DependencyResolver.SetResolver(new StructureMapContainer(new Container())); which uses invoker.

  8. SaintGimp says:

    I seem to remember running into that problem at some point, and I think the issue was that when you combine StructureMap's AssembliesFromApplicationBaseDirectory() registration function with the WithDefaultConventions() function, it will scan literally all of the types in all of the assemblies it finds in whatever folder contains your app's primary executable.  Some of those assemblies will be things your app references, like the MVC assemblies, and not all of the types in those assemblies are going to be amenable to scanning in that way (because some of them might not be suitable for automatic construction and DI).  The fix is to not do that – either scan all assemblies but only register certain types, or register all types but only in your own assemblies.

    By the way, I decided that the explicit registration of the controller types wasn't actually necessary, or at least I couldn't find a need for it, so I eventually removed it from my code.  I do general StructureMap registration for my app elsewhere, of course, so I can still construct objects from the container.

  9. frank says:

    Can you elaborate on your last comment. What do you mean elsewhere?

  10. Round Stickers says:

    I seem to consider managing into that issue at some factor, and I think the concern was that when you incorporate StructureMap's AssembliesFromApplicationBaseDirectory() signing up operate with the WithDefaultConventions() operate, it will check out basically all of the kinds in all of the devices it discovers in whatever directory contains your app's main exe.<a href="…/Round-Stickers.php">Round Stickers</a>