简单来说,我尝试在我的MVC3项目中使用Http Session为Unity框架创建Lifetime管理器。我的终身经理的示例实现是:
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
替换了默认的控制器工厂 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实际上是null,因此代码无法从会话中检索或保存到会话
知道为什么会话在这个阶段为空?
答案 0 :(得分:4)
我的错误,我应该将UnityPerSessionLifetimeManager
类的代码更改为
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函数中,会话状态已准备就绪。