using System;
namespace Com.W3oa.Hibernate
{
/// <summary>
/// Summary description for HibernateUtil.
/// </summary>
public sealed class HibernateUtil
{
[ThreadStatic]
private static NHibernate.ISession threadLocal;
private static NHibernate.ISessionFactory factory = null;
private static NHibernate.Cfg.Configuration configuration;
/// <summary>
/// 构造函数
/// </summary>
static HibernateUtil()
{
try
{
configuration = new NHibernate.Cfg.Configuration();
configuration.AddAssembly( System.Reflection.Assembly.GetExecutingAssembly());
factory = configuration.BuildSessionFactory();
}
catch(Exception ex)
{
throw new Exception("Could not create the NHibernate configuration", ex);
}
}
private HibernateUtil(){}
/// <summary>
/// 获取Session
/// </summary>
public static NHibernate.ISession GetSession()
{
if(threadLocal == null || !threadLocal.IsOpen)
{
try
{
threadLocal = (factory != null)?factory.OpenSession():null;
}
catch(Exception ex)
{
throw new Exception("The session or database connection could not be created",ex);
}
}
return threadLocal;
}
/// <summary>
/// 关闭Session
/// </summary>
public static void CloseSession()
{
if(threadLocal !=null)
{
threadLocal.Close();
threadLocal = null;
}
}
/// <summary>
/// 获取SessionFactory
/// </summary>
/// <returns></returns>
public static NHibernate.ISessionFactory GetSessionFactory()
{
return factory;
}
/// <summary>
/// 获取Configuration
/// </summary>
/// <returns></returns>
public static NHibernate.Cfg.Configuration GetConfiguration()
{
return configuration;
}
}
}