您可以創建一個複合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
一個實例。
通過獲取默認實例並將其傳遞到您的工廠,您可能還會考慮使您的工廠更具前瞻性(以防MVC的新版本從GetControllerFactory
開始返回不同類型;不太可能,但可能發生):
// in Global.asax
var defaultFactory = ControllerBuilder.Current.GetControllerFactory();
ControllerBuilder.Current.SetFactory(new EntityControllerFactory(defaultFactory));