熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

NHibernate中Session的處理

2022-06-13   來源: .NET編程 

  

  NHibernate中Session是線程不安全的而且每次數據庫操作 請求創建Session時對性能有些影響在Windows應用中可以通過 [ThreadStatic]特性很簡單的就可以實現線程安全而在Web中可以通過將Session與用於請求HttpContext綁定實現線程安全並且用戶當前請求時只有一個Session代碼如下

  ISessionManagecs

  using System;
using NHibernate;

  namespace CommercialJwsoftFrameworkPersistenceSessionManage
{
    /// <summary>
    /// 功能主要用於封裝第三方類庫操作數據庫的Session類現主要用於封裝NHibernate中的Session
    /// </summary>
    public interface ISessionManage
    {
        /// <summary>
        /// 獲取Session的一個實例
        /// </summary>
        /// <returns>返回實現NHibernateISession接口的類</returns>
        ISession Get();

  /// <summary>
        /// 設置Session的一個實例
        /// </summary>
        /// <param name=session>實現NHibernateISession接口的類</param>
        void Set(ISession session);
    }
}

  --------------------------------------------

  WebNHSessioncs

  using System;
using SystemWeb;
using NHibernate;

  namespace CommercialJwsoftFrameworkPersistenceSessionManage
{
    /// <summary>
    /// 功能此類用於Web應用NHibernate提供的Session有兩個缺陷
    ///       一方面是線程不安全的另一方面每次數據庫操作創建一個Session對程序性能有影響
    ///       因此通過將Session綁定到HttpContext上這樣每個用戶具有唯一的一個Session而且
    ///       在用戶的請求結束後關閉Session並自己釋放掉
    /// </summary>
    public class WebNHSession : ISessionManage
    {
        public WebNHSession()
        {

  }

  /// <summary>
        /// 獲取存儲到HttpContext中的實現NHibernateISession接口的類實例
        /// </summary>
        /// <returns>實現NHibernateISession接口的類實例當用戶之前沒有調用Set方法會返回Null</returns>
        public ISession Get()
        {
            return (ISession)HttpContextCurrentItems[SessionConfigManageSessionSourceItemName];
        }

  /// <summary>
        /// 存儲實現NHibernateISession接口的類實例到HttpContext中
        /// </summary>
        /// <param name=session>實現NHibernateISession接口的類實例</param>
        public void Set(ISession session)
        {
            if (session != null)
            {
                HttpContextCurrentItemsAdd(SessionConfigManageSessionSourceItemName session);
            }
            else
            {
                HttpContextCurrentItemsRemove(SessionConfigManageSessionSourceItemName);
            }
        }
    }
}
---------------------------------------------

  WinFormNHSessioncs

  using System;
using NHibernate;

  namespace CommercialJwsoftFrameworkPersistenceSessionManage
{
    /// <summary>
    /// 功能此類用於Windows應用NHibernate提供的Session有兩個缺陷
    ///       一方面是線程不安全的另一方面每次數據庫操作創建一個Session對程序性能有影響
    ///       因此通過線程變量獲取一個NHibernate Session的多個線程安全的實例而且線程變量使用後即釋放掉
    /// </summary>
    public class WinFormNHSession : ISessionManage
    {
        [ThreadStatic]
        private static ISession _threadSession = null;

  public WinFormNHSession()
        {
        }

  /// <summary>
        /// 獲取存儲到線程變量中的實現NHibernateISession接口的類實例
        /// </summary>
        /// <returns>實現NHibernateISession接口的線程安全的類實例當用戶之前沒有調用Set方法會返回Null</returns>
        public ISession Get()
        {
            if (_threadSession != null)
            {
                if (_threadSessionIsConnected)
                {
                    _threadSessionReconnect();
                }
            }
            return _threadSession;
        }

  /// <summary>
        /// 存儲實現NHibernateISession接口的類實例到線程變量中
        /// </summary>
        /// <param name=session>實現NHibernateISession接口的類實例</param>
        public void Set(ISession session)
        {
            if (_threadSessionIsConnected)
            {
                sessionDisconnect();
            }
            _threadSession = session;
        }
    }
}

  SessionFactorycs

  using System;
using SystemRuntimeRemoting;
using NHibernate;

  namespace CommercialJwsoftFrameworkPersistenceSessionManage
{
    /// <summary>
    /// 功能管理多個實現ISessionManage接口的類工廠根據讀取的要加載的類名稱信息進行動態的創建Session
    /// </summary>
    public class SessionFactory
    {
        private static ISession session = null;
        private static ISessionManage sessionManage = null;
       
        static SessionFactory()
        {
            Init();
        }

  /// <summary>
        /// 獲取實現NHibernateISession接口的Session實例
        /// </summary>
        /// <returns>返回實現NHibernateISession接口的類實例</returns>
        public static ISession GetSession()
        {
                      session = sessionManageGet();
          
            if (session == null)
            {
                session = NHibernateSessionGetNHibernateSession();
                sessionManageSet(session);
            }

  return session;
        }

  private static void Init()
        {
            SystemReflectionAssembly ass = SystemReflectionAssemblyLoad(SessionConfigManageAssemblyName);
            sessionManage = (ISessionManage)assCreateInstance(SessionConfigManageSessionSourceItemName);
        }
    }
}
----------------------------------------------

  NHibernateSessioncs

  using System;
using SystemData;
using SystemCollectionsGeneric;
using SystemText;
using NHibernate;
using NHibernateCfg;

  namespace CommercialJwsoftFrameworkPersistenceSessionManage
{
    /// <summary>
    /// 功能加載嵌入資源(Xml配置文件)打開一個SessionFactory獲取NHibernate的Session實例
    /// </summary>
    public class NHibernateSession
    {
        private static Configuration cfg = null;
        private static ISessionFactory sessionFactory = null;

  static NHibernateSession()
        {
            cfg = new Configuration()Configure();
            sessionFactory = cfgBuildSessionFactory();
        }

  /// <summary>
        /// 獲取NHibernate的Session實例
        /// </summary>
        /// <returns></returns>
        public static ISession GetNHibernateSession()
        {
            return sessionFactoryOpenSession();
        }
    }
}
---------------------------------------------

  SessionConfigManagecs

  using System;
using SystemCollectionsGeneric;
using SystemText;
using SystemConfiguration;

  namespace CommercialJwsoftFrameworkPersistenceSessionManage
{
    /// <summary>
    /// 功能根據類庫的應用環境不同(Windows應用還是Web應用)動態創建類實例
    /// 日期
    /// 作者郭少宏
    /// </summary>
    public class SessionConfigManage
    {
        private const string SESSION_ITEM_NAME = SessionItemName;
        private static object _locker = new object();
        private static string _sessionItemName = stringEmpty;
        private static string _assemblyName = stringEmpty;

  static SessionConfigManage()
        {
            string configString = ConfigurationManagerAppSettings[SESSION_ITEM_NAME];
            string[] arr = configStringSplit();
            _sessionItemName = arr[];
            _assemblyName = arr[];
        }
        /// <summary>
        /// 獲取配置文件中名為SESSION_ITEM_NAME配置節的信息記錄的要加載的SessionManage的類全稱
        /// </summary>
        /// <returns>實現ISessionManage接口的類的名稱</returns>
        public static string SessionSourceItemName
        {
            get
            {
                lock (_locker)
                {
                    return _sessionItemName;
                }
            }
        }

  /// <summary>
        /// 獲取配置文件中名為SESSION_ITEM_NAME配置節的信息記錄的要加載的SessionManage的類全稱
        /// </summary>
        /// <returns>實現ISessionManage接口的類的程序集名稱</returns>
        public static string AssemblyName
        {
            get
            {
                lock (_locker)
                {
                    return _assemblyName;
                }
            }
        }
    }
}

  在WebConfig文件中的配置節如下

  <appSettings>
    <!>
    <!在Web應用中加載的獲取Session的類名稱>
    <add key=SessionItemName value=CommercialJwsoftFrameworkPersistenceSessionManageWebNHSessionJWFramework/>
    <!在Windows應用中加載的獲取Session的類名稱>
    <!<add key=SessionItemName value=CommercialJwsoftFrameworkPersistenceSessionManageWinFormNHSessionJWFramework/>>
  </appSettings>

  在Globalasax中添加如下代碼

  /// <summary>
    /// 當用戶斷開請求時用來關閉用戶請求的Session的連接
    /// </summary>
    /// <param name=sender></param>
    /// <param name=e></param>
  void Session_End(object sender EventArgs e)
    {
        NHibernateISession session = CommercialJwsoftFrameworkPersistenceSessionManageSessionFactoryGetSession();
        if (session != null)
        {
            sessionClose();
        }

  }


From:http://tw.wingwit.com/Article/program/net/201311/13675.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.