gpt4 book ai didi

asp.net-mvc-3 - MVC3、Unity 框架和每 session 生命周期管理器问题

转载 作者:行者123 更新时间:2023-12-03 18:18:02 25 4
gpt4 key购买 nike

简而言之,我尝试通过在我的 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 替换了默认 Controller 工厂
    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 的每个函数上设置了断点类,我注意到当 Controller 工厂试图解决我的 Controller 的依赖关系时,HttpContext.Session 实际上是空的,所以代码无法从 session 中检索或保存到 session 。

知道为什么 session 在这个阶段为空吗?

最佳答案

我的错误,我应该更改 UnityPerSessionLifetimeManager 的代码类(class)

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;
}
}

因为当构造函数被调用来注册类型时, session 状态还没有准备好,我已经将当时的 http 上下文分配给了一个变量。但在稍后的 Get/Set 函数 session 状态已准备就绪。

关于asp.net-mvc-3 - MVC3、Unity 框架和每 session 生命周期管理器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9178862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com