NHibernate.HibernateException: No session bound to the current context

Miral picture Miral · Jul 17, 2009 · Viewed 14.2k times · Source

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

NHibernate.Context.CurrentSessionContext.CurrentSession()

at

NHibernate.Impl.SessionFactoryImpl.GetCurrentSession()

Answer

CalebHC picture CalebHC · Jul 18, 2009

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.