NHibernate, Part 3 of xxx: NHibernate Session Management

March 16, 2005

Continuing my rant about NHibernate being a whole lot of stuff to learn, it's also somewhat difficult to know how to actually do things the “right way”.

A big one for me was trying to figure out the best way to manage NHibernate sessions from an ASP.NET application.  If you were doing a Windows Forms application with NHibernate, it would be pretty easy to manage the session.  You'd open the session and probably put it in a static variable somewhere.

Well, that kinda doesn't really work out so well for an ASP.NET application because that static variable is a Singleton to the app domain so it'll be shared across all requests.  Sounds like a threading nightmare waiting to happen.

Then there's the option of putting the NHibernate session into the ASP.NET Session.  That's stinky because it could be open for a really long time and there isn't really any bulletproof way to kill the NHibernate session if the ASP.NET Session gets abandoned or otherwise shut down.

And then there's thread local storage blah blah blah that doesn't work out well either for some reason blah blah blah.

Whatever.  Bottom line.  There are a whole mess of options that stink and no real rock-solid consensus on the news groups about what to do.  There's some agreement that opening up an NHibernate session for every web request will work but it took some digging to find that.  There was some sample code but not a complete working example.

So.  It's not fantastic but it's something.  I started writing a bug tracker sample application as a proof of concept using NHibernate.  http://www.benday.com/temp/BugTrackerNHibernateSample.zip  It has a ASP.NET user interface and a Windows Forms user interface.  I've included a backup of my “bugs“ database.

The key thing to look at is the NHibernateHttpModule in Com.Benday.BugTracker.DataAccess and how it gets registered in web.config.  This module gets loaded and creates an NHibernate session that exists for the duration of the http web request.  I based this largely (translation: entirely) on Ed Courtenay's code that he posted at http://sourceforge.net/forum/message.php?msg_id=2847509.  I think it works pretty well.

Feel free to critique the approach.  I know that what I'm doing with NHibernate probably isn't perfect.

-Ben

FYI, other posts on NHibernate are available here.

Categories: tech