Created
September 19, 2012 19:03
-
-
Save jkodroff/3751537 to your computer and use it in GitHub Desktop.
Using ASP.NET MVC with StructureMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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