最近测试NHibernate的时候,模拟HibernateUtil做了一个工具类NHibernateUtil.感觉挺不错的,所以拿出来与大家分享.请各位同道指正.
using System;
namespace Com.W3oa.Hibernate
{
/// <summary>
/// Summary description for SessionFactory.
/// </summary>
public class NHibernateUtil
{
[ThreadStatic]
private static NHibernate.ISession threadLocal;
private static NHibernate.ISessionFactory sessionFactory = null;
/// <summary>
/// 构造函数
/// </summary>
static NHibernateUtil()
{
if (sessionFactory == null )
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.AddAssembly( System.Reflection.Assembly.GetExecutingAssembly());
sessionFactory = cfg.BuildSessionFactory();
}
}
private NHibernateUtil(){}
/// <summary>
/// 获取HibernateSession
/// </summary>
public static NHibernate.ISession Session
{
get
{
NHibernate.ISession session = (NHibernate.ISession)threadLocal;
if(session == null||!session.IsOpen)
{
session = sessionFactory.OpenSession();
threadLocal = session;
}
return session;
}
}
/// <summary>
/// 关闭HibernateSession
/// </summary>
public static void CloseSession()
{
NHibernate.ISession session = threadLocal;
threadLocal = null;
if (session != null)
{
session.Close();
}
}
}
}