Just sharing some of my inconsequential lunch conversations with you... RSS  

Wednesday, July 11, 2007

NHibernate: LazyInitializationException

A common issue in a typical web application is the rendering of the view after the main logic of the action has been completed, and therefore, the NHibernate Session has already been closed and the database transaction has ended. If you access detached objects that have been loaded in the Session inside your ASPX, you might hit an unloaded collection or a proxy that isn't initialized - this is a common problem with datagrid databinding. The exception you get is: LazyInitializationException: Session has been closed (or a very similar message). Of course, this is to be expected, after all you already ended your unit of work.

The solution often presented is to set an HTTP interceptor to ensure session lifetime (namely: nhibernate.org, where most of this post was taken from). On my first NHibernate project, I've decided to wrap it up on my DataPage, a session aware class deriving from System.UI.Web.Page. With this simple solution I can easily differentiate session aware pages.

No comments:

Development Catharsis :: Copyright 2006 Mário Romano