问题描述
在一个简单的字,我尝试在我的MVC3项目中使用HTTP会话创建统一的框架终身经理。我的一生经理实现示例:
In a simple word I try to create Lifetime manager for Unity framework by using Http Session in my MVC3 project. My sample implementation of lifetime manager is:
public class UnityPerSessionLifetimeManager : LifetimeManager
{
private string sessionKey;
private HttpContext ctx;
public UnityPerSessionLifetimeManager(string sessionKey)
{
this.sessionKey = sessionKey;
this.ctx = HttpContext.Current;
}
public override object GetValue()
{
return this.ctx.Session[this.sessionKey];
}
public override void RemoveValue()
{
this.ctx.Items.Remove(this.sessionKey);
}
public override void SetValue(object newValue)
{
this.ctx.Session[this.sessionKey] = newValue;
}
}
在我的global.asax.cs我取代默认的控制器工厂与我自己的UnityControllerFactory
In my global.asax.cs I replaced default controller factory with my own UnityControllerFactory
public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer container;
public UnityControllerFactory(IUnityContainer container)
{
this.container = container;
this.RegisterServices();
}
protected override IController GetControllerInstance(RequestContext context, Type controllerType)
{
if (controllerType != null)
{
return this.container.Resolve(controllerType) as IController;
}
return null;
}
private void RegisterServices()
{
this.container.RegisterType<IMyType, MyImpl>(new UnityPerSessionLifetimeManager("SomeKey"));
}
}
}
我设置的断点上 UnityPerSessionLifetimeManager
类的每一个功能,我注意到,当控制器工厂试图解决我的控制器相依,HttpContext.Session实际上是空的,所以code未能从会话中检索或保存到会话中。
I set breakpoints on each function of UnityPerSessionLifetimeManager
class, I noticed that when controller factory tries to solve dependencies of my controller, the HttpContext.Session is actually null, so the code fails retrieve from session or save to session.
任何想法,为什么会是空在这个阶段?
Any idea why session is null at this stage?
推荐答案
我的错,我应该改变 UnityPerSessionLifetimeManager
类是
My mistake, I should change code of UnityPerSessionLifetimeManager
class to be
public class UnityPerSessionLifetimeManager : LifetimeManager
{
private string sessionKey;
public UnityPerSessionLifetimeManager(string sessionKey)
{
this.sessionKey = sessionKey;
}
public override object GetValue()
{
return HttpContext.Current.Session[this.sessionKey];
}
public override void RemoveValue()
{
HttpContext.Current.Session.Remove(this.sessionKey);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Session[this.sessionKey] = newValue;
}
}
因为当构造函数被调用登记类型,会话状态还没有准备好,我已经分配的那段时间HTTP上下文给一个变量。但在以后的get / set函数的会话状态已准备就绪。
because when the constructor was called to register type, session state is not ready yet and I already assigned http context of that time to a variable. But in later Get/Set functions session state is ready.
这篇关于MVC3,统一框架和每会话生命周期管理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!