Posterous theme by Cory Watilo

ASP.NET MVC, StructureMap, and the 404

ASP.NET has a great mechanism for handling 404's in an elegant way. In a purely declarative manner you can add the following to your Web.config:
This works great when you are using ASP.NET, but when you're using StructureMap (or any IoC container) to override the DefaultControllerFactory in ASP.NET MVC you have a bit of a problem in finding the non-existent controller type...namely...an Exception. For example, here's what I'm doing with the controller factory and StructureMap:
public class InjectionControllerFactory : DefaultControllerFactory {
    protected override IController GetControllerInstance(Type controllerType) {
        return ObjectFactory.GetInstance(controllerType) as Controller;
    }
}
The problem is that when controllerType is null (i.e. there is no controller for the given URL) then an exception is thrown in the call to ObjectFactory.GetInstance. So our fancy error setup in the Web.config is moot because an exception is thrown before we even get there. So, how do we fix this? Well...it's simple really...let MVC do it's thing. The DefaultControllerFactory method that we're overriding here already handles this situation gracefully, so just call the base method if the ObjectFactory.GetInstance call can't be completed.
public class InjectionControllerFactory : DefaultControllerFactory {
    protected override IController GetControllerInstance(Type controllerType) {
        if (controllerType != null) {
            return ObjectFactory.GetInstance(controllerType) as Controller;
        return base.GetControllerInstance(controllerType);
    }
}
Voila, now our "virtual" 404 is handled and our special 404 page is displayed.
| Viewed
times | Favorited 0 times
Filed under:  

1 Comment

Mar 15, 2009
ASP.NET MVC Archived Blog Posts, Page 1 said...
[...] to VoteASP.NET MVC, StructureMap, and the 404 — The Grubbsian (3/13/2009)Friday, March 13, 2009 from JC GrubbsASP.NET MVC, StructureMap, and the 404 was posted on March [...]

Leave a comment...