在我的項目中,我圍繞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