Asp.net mvc 3 MVC3、Unity框架和每会话生命周期管理器问题
简单地说,我试图通过在MVC3项目中使用Http会话为Unity框架创建Lifetime manager。我的lifetime manager示例实现是:Asp.net mvc 3 MVC3、Unity框架和每会话生命周期管理器问题,asp.net-mvc-3,unity-container,Asp.net Mvc 3,Unity Container,简单地说,我试图通过在MVC3项目中使用Http会话为Unity框架创建Lifetime manager。我的lifetime manager示例实现是: public class UnityPerSessionLifetimeManager : LifetimeManager { private string sessionKey; private HttpContext ctx; public UnityPerSessionL
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中,我用自己的UnityController工厂替换了默认的控制器工厂
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"));
}
}
}
公共类UnityController工厂:DefaultControllerFactory
{
专用IUnityContainer容器;
公共UnityController工厂(IUnityContainer容器)
{
this.container=容器;
这是RegisterServices();
}
受保护的重写IController GetControllerInstance(RequestContext上下文,类型controllerType)
{
if(controllerType!=null)
{
将此.container.Resolve(controllerType)作为IController返回;
}
返回null;
}
私有无效注册表服务()
{
this.container.RegisterType(新的UnityPerSessionLifetimeManager(“SomeKey”);
}
}
}
我在UnityPerSessionLifetimeManager
类的每个函数上设置了断点,我注意到当控制器工厂试图解决控制器的依赖项时,HttpContext.Session实际上为空,因此代码无法从会话检索或保存到会话
知道为什么会话在这个阶段是空的吗?我错了,我应该将
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函数中,会话状态已准备就绪