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.
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.