加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – MVC3,Unity Framework和Per Session Lifetime

发布时间:2020-12-16 10:01:43 所属栏目:asp.Net 来源:网络整理
导读:简单来说,我尝试在我的MVC3项目中使用Http Session为Unity框架创建Lifetime管理器.我的终身经理的示例实现是: public class UnityPerSessionLifetimeManager : LifetimeManager { private string sessionKey; private HttpContext ctx; public UnityPerSess
简单来说,我尝试在我的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,因此代码无法从会话检索或保存到会话.

知道为什么会话在这个阶段为空?

解决方法

我的错误,我应该改变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函数中,会话状态已准备就绪.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读