NHibernate.HibernateException: No session bound to the current context

只愿长相守 提交于 2019-12-22 10:35:18

问题


I am getting this error when I am trying to get the CurrentSession

NHibernate.Context.CurrentSessionContext.CurrentSession()

at

NHibernate.Impl.SessionFactoryImpl.GetCurrentSession()

回答1:


You are responsible for setting the current session on the session context. See this section of the NHibernate documentation. If you haven't done this, then there will be no current session to retrieve.




回答2:


Like David M said, you need to make sure you are binding your NHibernate session. Here's the way I do it right now in my ASP.NET app:

public class NHHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.EndRequest += ApplicationEndRequest;
        context.BeginRequest += ApplicationBeginRequest;
    }

    public void ApplicationBeginRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Bind(NHSessionFactory.GetNewSession());
    }

    public void ApplicationEndRequest(object sender, EventArgs e)
    {
        ISession currentSession = CurrentSessionContext.Unbind(
            NHSessionFactory.GetSessionFactory());
        currentSession.Close();
        currentSession.Dispose();
    }

    public void Dispose()
    {
        // Do nothing
    }
}

I create a custom HttpModule that binds my session on every request and then I add this module to my web.config like this:

<httpModules>
  <add name="NHHttpModule" type="MyApplication.Core.NHHttpModule, MyApplication,
  Version=1.0.0.0, Culture=neutral" />      
</httpModules>

I'm sure your configuration is different then this but this is just an example of how I bind my session. Hope this helps a little.




回答3:


Studio 2010 will create 2 httpModules sections, one is for IIS 7. Be sure to register your nhibernate httpmodule in the system.web one too.



来源:https://stackoverflow.com/questions/1143611/nhibernate-hibernateexception-no-session-bound-to-the-current-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!