views:

323

answers:

2

New to NHibernate(my disclaimer). I came across a similar and interesting article regarding MVC, however, I'm more curious as to what general best practices are for managing NHibernate sessions within a generic web application.

I've come across the Burrow project, but I'm starting to realize there seems to be a few different directions to take. I'm aware it's probably not in my best interest to create a new SessionFactory every time I need to touch the database, so I'm interested in what the community does to manage sessions. Do you use Burrow? Do you wrap your SessionFactory in a singleton?

Any direction or insight is always greatly appreciated.

+2  A: 

I wrote a series of blog posts on this topic regarding with NHibernate / Fluent NHibernate Data Access patterns.

The first I recommend is abstract away the interaction of NHibernate.

Creating a common generic and extensible NHiberate Repository

Then for handling session management I implemented the "Session per Business Conversation" pattern which instead of having a NH session exist for the life of a single page request that is a common one it exists for a series of events say a page that allows you to make a bunch of edits to a form and then at the end either apply them all permanently or cancel them.

Conversation Per Business Transaction using PostSharp and IoC

If I was going to write this post today, I wouldn't use PostSharp again to handle the AOP (Aspect Orientated Programming) code in my project I'd either use Linfu.AOP or another framework to do the AOP interaction.

Chris Marisic
'Creating a common generic and extensible NHiberate Repository' was a great read.
Ben Clark-Robinson
I appreciate the feedback, thanks Ben!
Chris Marisic
+3  A: 

To answer your question directly, your ISessionFactory object should be a singleton. You can either do this programmatically (i.e. by wrapping it in a C# singleton) or by configuring it in your IoC container.

As for sessions, Burrow looks good but the prodominant and simplest pattern for sessions in web applications - OpenSessionInView - comes out-of-the-box with NHibernate 2.0.0. That is, your data access code calls ISessionFactory.GetCurrentSession() rather than ISessionFactory.OpenSession(). You then state how the factory's current session is managed by specifying an implementation of ICurrentSessionContext. NHibernate provides two out-of-the box ones for alligning the session with the web request. This is known as 'Contextual Sessions' in the documentation.

No doubt a more complex web application might require more longer lasting conversations with complex lazy loading etc., but for a standard web application NHibernate contextual sessions should suffice.

Andy Grout