Saturday, August 30, 2008

Context Based Sessions in NHibernate

I have seen a lot of people asking questions about creating context based Sessions in NHibernate. One of the solutions that people have suggested is to create a new Session Factory for each database. This solution sounds attractive, but will become problematic as the application scales up. In this post I would to share my solution that we implement in my current project.

NHibernate lets the developer provider their own connection. As we were using Open Session in View strategy we decided to pass the connection string to create a session using ISessionFactory. OpenSession(IdbConnection obj). By using this technique NHibernate’s second level cache is disabled. For our application we were not interested in using a second level cache so it didn’t matter. If you are interested in using second level cache solution is to implement your own IConnectionProvider. Information about which database to use can be passed using HttpContext.Items.

NHibernate context is feature that is very rarely talked about. NHibernate Session Factory provides a method GetCurrentSession() this lets you get current session in the context. NHibernate provides built in implementation for web application. For more information please review section 2.3 of NHibernate documentation. This way the DAO and Business Object don’t have to worry about how to create the session and remain agnostic of which database they are connecting to.

Please comment. Thanks