Best practice for NHibernate: Don’t store references to ISession-instances

Do you see any (or all) of these exceptions (NHibernate.ADOException) in you NHibernate-based web application?

could not execute query
failed to lazily initialize a collection, no session or session was closed
Transaction not successfully started
The server failed to resume the transaction. Desc:86000002dc.

If you do, it might be a good idea to make sure you don’t store any ISession-references anywhere. If you do there’s a great risk that something goes wrong if two threads (i.e. two requests) are using the session at the same time as the NHibernate session implementation is not thread safe.

Instead, do this when an ISession is needed:

ISession session = SessionFactory.Factory.GetCurrentSession();

That code will get the session from the current context (which of course must be updated by your code, look here for more info).


2 thoughts on “Best practice for NHibernate: Don’t store references to ISession-instances”

  1. I tried to implement this and, sadly, only the CallSessionContext worked. I was unable to get either the WebSessionContext or ManagedWebSessionContext to work. I looked at the source to see if there was something I was doing wrong and there were no tests written for any of these context objects. I was also unable to find any examples of using WebSessionContext or ManagedWebSessionContext.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.