在Global.asax中的Application_Start()方法中,您需要将ControllerBuilder.Current替换为控制器工厂的自定义实现 .
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var controllerFactory = new CustomControllerFacotry();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
}
您需要一个类继承DefaultControllerFactory并使用您的自定义实现覆盖CreateController方法 . 请查看默认实现,以获取有关如何执行此操作的进一步指导 . 它看起来像这样 .
public class CustomControllerFactory : DefaultControllerFactory
{
public override IController CreateController(RequestContext requestContext, string controllerName)
{
string controllername = requestContext.RouteData.Values["controller"].ToString();
Type controllerType = Type.GetType(string.Format("Namespace.{0}",controllername));
IController controller = Activator.CreateInstance(controllerType) as IController;
return controller;
}
}