我有一个MVC 5应用程序。我使用Unity作为我的DI。 在我的应用程序中,我有两个动作控制器:
我的主要Action视图调用Html.RenderAction(" ChildAction")。
我收到下一个错误:
A single instance of controller '' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.
我尝试了很多解决方案,例如创建自定义" UnityControllerFactory":
public class UnityControllerFactory : DefaultControllerFactory
{
IUnityContainer container;
public UnityControllerFactory(IUnityContainer container)
{
this.container = container;
}
public override IController CreateController(RequestContext context, string controllerName)
{
Type type = GetControllerType(context, controllerName);
if (type == null)
{
throw new InvalidOperationException(string.Format("Could not find a controller with the name {0}", controllerName));
}
return (IController)container.Resolve(type);
}
protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
{
IController controller;
if (controllerType == null)
throw new HttpException(
404, String.Format(
"The controller for path '{0}' could not be found" +
"or it does not implement IController.",
reqContext.HttpContext.Request.Path));
if (!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(
string.Format(
"Type requested is not a controller: {0}",
controllerType.Name),
"controllerType");
try
{
controller = container.Resolve(controllerType)
as IController;
}
catch (Exception ex)
{
throw new InvalidOperationException(String.Format(
"Error resolving controller {0}",
controllerType.Name), ex);
}
return controller;
}
public override void ReleaseController(IController controller)
{
container.Teardown(controller);
}
使用" TransientLifetimeManager":
注册控制器container.RegisterType<TestController>(new TransientLifetimeManager());
没有任何效果。
我们将不胜感激。