Nhibernate session management strategy for web application with background-workers?

后端 未结 3 1369
灰色年华
灰色年华 2021-01-06 00:46

For a web application, it seems like a good way to handle the session is to use the setting managed_web

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 01:22

    I solved it by creating my own session context class:

    public class HybridWebSessionContext : CurrentSessionContext
    {
        private const string _itemsKey = "HybridWebSessionContext";
        [ThreadStatic] private static ISession _threadSession;
    
        // This constructor should be kept, otherwise NHibernate will fail to create an instance of this class.
        public HybridWebSessionContext(ISessionFactoryImplementor factory)
        {
        }
    
        protected override ISession Session
        {
            get
            {
                var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
                if (currentContext != null)
                {
                    var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
                    var session = items[_itemsKey] as ISession;
                    if (session != null)
                    {
                        return session;
                    }
                }
    
                return _threadSession;
            }
            set
            {
                var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
                if (currentContext != null)
                {
                    var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
                    items[_itemsKey] = value;
                    return;
                }
    
                _threadSession = value;
            }
        }
    }
    

提交回复
热议问题