是否可以用与what can be done with Web API类似的方式为在简单注入器中注册的Mvc控制器注册自定义IHttpControllerActivator
?
我运行DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
时,也会将简单的注射器插入我的第三方控制器中,这是我想避免的。
答案 0 :(得分:0)
根据史蒂文在评论中的建议,我提出了以下建议:
public class MvcControllerFactory : DefaultControllerFactory
{
private readonly Container _container;
private readonly IControllerFactory _original;
public MvcControllerFactory(
Container container, IControllerFactory original)
{
_container = container;
_original = original;
}
protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
return null;
}
if (controllerType == typeof(MyMvcController))
{
return (IController)_container.GetInstance(controllerType);
}
var controllerName = requestContext.RouteData.GetRequiredString("controller");
if (!string.IsNullOrEmpty(controllerName))
{
return _original.CreateController(requestContext, controllerName);
}
return (IController) Activator.CreateInstance(controllerType);
}
}
在我的应用程序开始:
var original = ControllerBuilder.Current.GetControllerFactory();
var controllerFactory = new MvcControllerFactory(container, original);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);