Created
July 3, 2012 10:51
-
-
Save hvitorino/3039033 to your computer and use it in GitHub Desktop.
ControllerFactory
This file contains hidden or 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
| public class ControllerFactory : DefaultControllerFactory | |
| { | |
| public override IController CreateController(RequestContext requestContext, string controllerName) | |
| { | |
| IController controllerInstance = null; | |
| try | |
| { | |
| controllerInstance = base.CreateController(requestContext, controllerName); | |
| } | |
| catch (System.Exception) | |
| {} | |
| if (controllerInstance != null) | |
| return controllerInstance; | |
| var controllerType = GetControllerType(controllerName); | |
| return base.GetControllerInstance(requestContext, controllerType); | |
| } | |
| private System.Type GetControllerType(string controllerName) | |
| { | |
| var extractedName = ExtractControllerName(controllerName); | |
| var controllerType = this.GetType().Assembly.GetTypes() | |
| .Where(type => type.Name == extractedName && type.IsSubclassOf(typeof(Controller))) | |
| .FirstOrDefault(); | |
| return controllerType; | |
| } | |
| private static string ExtractControllerName(string controllerName) | |
| { | |
| var words = controllerName.Split(new char[] { '-' }); | |
| var extractedName = string.Empty; | |
| foreach (var word in words) | |
| extractedName += word[0].ToString().ToUpper() + word.Substring(1); | |
| return extractedName + "Controller"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment