在我的项目中,我围绕CurrentSessionContext写了一个小包装类。
也许你可以扩展它来满足你的需求。
我想你只需要调整的BindSessionToRequest
和GetCurrentSession
实施:
public static class SessionManager
{
private static ISessionFactory _sessionFactory = null;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
//check whether we're in web context or win context, and create the session factory accordingly.
if (System.Web.HttpContext.Current != null)
{
if (_sessionFactory == null)
{
_sessionFactory = DAOBase.GetSessionFactory();
}
}
else
{
_sessionFactory = DAOBase.GetSessionFactoryForWin();
}
}
return _sessionFactory;
}
}
public static void BindSessionToRequest()
{
ISession session = SessionManager.SessionFactory.OpenSession();
NHibernate.Context.CurrentSessionContext.Bind(session);
}
public static bool CurrentSessionExists()
{
return NHibernate.Context.CurrentSessionContext.HasBind(SessionFactory);
}
public static void UnbindSession()
{
ISession session = NHibernate.Context.CurrentSessionContext.Unbind(SessionManager.SessionFactory);
if (session != null && session.IsOpen)
{
session.Close();
}
}
public static ISession GetCurrentSession()
{
return SessionFactory.GetCurrentSession();
}
}
如果你不想引用'HttpContext.Current',你可以使用'NHibernate.Context.ReflectiveHttpContext'来确定一个上下文是否可用。例如,在您不想在数据访问项目中引用'System.Web'的情况下,这非常有用。 – Siewers 2011-07-06 17:43:04
谢谢你,小费!我编辑了代码来代替它! :) – Allrameest 2011-07-07 11:52:08
非常感谢你!一直困惑了半天 - 我有一个WCF服务的WebForms项目,'CurrentSessionContext.Bind'抛出'NullReferenceException'。你的代码对我来说是完美无缺的:D – 2014-02-20 06:58:42