您可以创建一个复合IControllerFactory
实现:
public class EntityControllerFactory : IControllerFactory {
private IControllerFactory defaultFactory = new DefaultControllerFactory();
public IController CreateController(RequestContext requestContext, string controllerName) {
if(needsCustomLogic) {
// do your custom logic here and return appropriate result
} else {
return defaultFactory.CreateController(requestContext, controllerName);
}
}
// same for the other methods on IControllerFactory
}
这是可行的,因为默认情况下 的值ControllerBuilder.Current.GetControllerFactory()
是 的实例DefaultControllerFactory
。
GetControllerFactory
您还可以考虑通过获取默认实例并将其传递给您的工厂,使您的工厂更具前瞻性(以防新版本的 MVC 开始返回不同的类型;不太可能,但它可能发生):
// in Global.asax
var defaultFactory = ControllerBuilder.Current.GetControllerFactory();
ControllerBuilder.Current.SetFactory(new EntityControllerFactory(defaultFactory));