我对 unity 中的生命周期管理器有一些问题,它像单例一样使用对象,但在配置中我将它设置为“PerWebRequest”。
错误是: Controller “TestController”的单个实例不能用于处理多个请求。如果正在使用自定义 Controller 工厂,请确保它为每个请求创建一个新的 Controller 实例。
PerWebRequest 代码:
public class UnityPerWebRequestLifetimeManager : LifetimeManager
{
private HttpContextBase _httpContext;
public UnityPerWebRequestLifetimeManager()
: this(new HttpContextWrapper(HttpContext.Current))
{
}
public UnityPerWebRequestLifetimeManager(HttpContextBase httpContext)
{
_httpContext = httpContext;
}
private IDictionary<UnityPerWebRequestLifetimeManager, object> BackingStore
{
get
{
_httpContext = (HttpContext.Current != null) ? new HttpContextWrapper(HttpContext.Current) : _httpContext;
return UnityPerWebRequestLifetimeModule.GetInstances(_httpContext);
}
}
private object Value
{
[DebuggerStepThrough]
get
{
IDictionary<UnityPerWebRequestLifetimeManager, object> backingStore = BackingStore;
return backingStore.ContainsKey(this) ? backingStore[this] : null;
}
[DebuggerStepThrough]
set
{
IDictionary<UnityPerWebRequestLifetimeManager, object> backingStore = BackingStore;
if (backingStore.ContainsKey(this))
{
object oldValue = backingStore[this];
if (!ReferenceEquals(value, oldValue))
{
IDisposable disposable = oldValue as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
if (value == null)
{
backingStore.Remove(this);
}
else
{
backingStore[this] = value;
}
}
}
else
{
if (value != null)
{
backingStore.Add(this, value);
}
}
}
}
[DebuggerStepThrough]
public override object GetValue()
{
return Value;
}
[DebuggerStepThrough]
public override void SetValue(object newValue)
{
Value = newValue;
}
[DebuggerStepThrough]
public override void RemoveValue()
{
Value = null;
}
}
Controller :
public class TestController : Controller
{
//
// GET: /Test/
public TestController()
{
}
public ActionResult Index()
{
return View();
}
public ActionResult RadioButtonList()
{
return View("TestControl");
}
}
Controller 工厂:
public class ControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return (controllerType == null) ? base.GetControllerInstance(requestContext, controllerType) : IoC.Resolve<IController>(controllerType);
}
}
在其中一个 View 中,我尝试这样使用它:
...
<% Html.RenderAction<TestController>(c => c.RadioButtonList()); %>
<% Html.RenderAction<TestController>(c => c.RadioButtonList()); %>
...
我不知道这里有什么问题?
谢谢。
最佳答案
两个统一 Controller 请求都是在同一个 HTTP 请求/回复中创建的,因此你得到了同一个实例。您需要进行切换,以便 Controller 具有 transient 生命周期。
我会切换到 DependencyResolver
而不是使用 ControllerFactory
因为你运行的是 MVC3。
关于asp.net-mvc-3 - controller 'TestController' 单个实例不能用于处理多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7497801/