Skip to content

Instantly share code, notes, and snippets.

@hvitorino
Created July 3, 2012 10:51
Show Gist options
  • Select an option

  • Save hvitorino/3039033 to your computer and use it in GitHub Desktop.

Select an option

Save hvitorino/3039033 to your computer and use it in GitHub Desktop.
ControllerFactory
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