NHibernate.HibernateException: Session not associated with current context

I get this error when I try to get CurrentSession

NHibernate.Context.CurrentSessionContext.CurrentSession() 

at

 NHibernate.Impl.SessionFactoryImpl.GetCurrentSession() 
+3
source share
3 answers

You are responsible for setting up the current session in the context of the session. See this section of the NHibernate documentation. If you have not already done so, there will be no current session to retrieve.

+6
source

As David M said, you need to make sure you bind your NHibernate session. Here's how I do it right now in my ASP.NET application:

 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 for each request, and then add this module to my web.config as follows:

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

I'm sure your configuration is different from this, but this is just an example of how I bind a session. Hope this helps a bit.

+13
source

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

+11
source

All Articles