First, I need a registry (that’s just ScructureMap, nothing really to do with MVC).
//The most simple registry I could think of
Then, in MVC 2, you needed to make your own
ControllerFactory (actually, you could get this from the MvcContrib project, if it was up to date):
public class StructureMapControllerFactory : DefaultControllerFactory
And finally, you needed to replace the default
ControllerFactory with the
public class MvcApplication : HttpApplication
Not the most difficult thing in the world, but still some amount of work.
Ok, what do you do in MVC 3? First of all, we still need our Registry, since that is how we setup StructureMap. But we don’t need our ControllerFactory at all! Instead, MVC 3 introduces a DependencyResolver with 3 methods:
public static void SetResolver(IDependencyResolver resolver);
So, instead of creating a
ControllerFactory, you can create a
DependencyResolver, which is more general, and only needs two simple methods:
GetServices. However, an even easier way to do it, which I like, is to use the last overload. So, in
Application_Start, we get:
And that’s all we need! And anywhere that MVC needs to resolve a dependency it will use this. And if it fails to resolve (i.e. returns null), it will just fall back to the default way. Me like!