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:
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.
Voila, now our "virtual" 404 is handled and our special 404 page is displayed.
public class InjectionControllerFactory : DefaultControllerFactory {
protected override IController GetControllerInstance(Type controllerType) {
return ObjectFactory.GetInstance(controllerType) as Controller;
}
}public class InjectionControllerFactory : DefaultControllerFactory {
protected override IController GetControllerInstance(Type controllerType) {
if (controllerType != null) {
return ObjectFactory.GetInstance(controllerType) as Controller;
return base.GetControllerInstance(controllerType);
}
}