Skip to content

Instantly share code, notes, and snippets.

@jkodroff
Created September 19, 2012 19:03
Show Gist options
  • Save jkodroff/3751537 to your computer and use it in GitHub Desktop.
Save jkodroff/3751537 to your computer and use it in GitHub Desktop.
Using ASP.NET MVC with StructureMap
Global.asax.cs:
public class MvcApplication : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// ...
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
StructureMapControllerFactory.cs
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
Throw404(requestContext);
try
{
return (IController)ObjectFactory.GetInstance(controllerType);
}
catch (InvalidOperationException ex)
{
if (ex.Message.Contains("did not return a controller for the name"))
{
Throw404(requestContext);
}
throw;
}
}
private static void Throw404(RequestContext requestContext)
{
var message =
"The controller for path '{0}' was not found or does not implement IController.".ToFormat(
requestContext.HttpContext.Request.Path);
throw new HttpException(404, message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment