views:

997

answers:

4

I am using NHibernate on a new ASP.NET project, and am running into what I believe to be strange behavior. I am attempting to manage my session by using an HttpModule to catch the EndRequest event and close the session. This is working fine, however, after the EndRequest event fires, I am getting an exception in the OnLoad event of one of my custom controls that is attempting to read a Property from my object that is lazy loaded. I get an exception stating 'failed to lazily initialize a collection, no session or session was closed'. Turning lazy load off for these properties does fix the problem, and is an acceptable solution. But this seems to be going against what I always thought to be true.

I would assume that the OnLoad event and all server side processing would be done at the point that EndRequest is fired. This is also the first time that I have used IIS 7 on a project. Is this a reason for the behavior? What is the expected behavior?

+1  A: 
  1. If your object is lazy-init and no session is open, resolving the properties will fail.
  2. Remember that lazy exceptions will most probably appear when you have some relationship with another entity that hasn't been initialized.

http://forum.springframework.org/showthread.php?t=13474

I would also recommend using something like the HTTP Module in Rhino Commons to manage your NHibernate Sessions.

Ryan Montgomery
A: 

use HttpModule if you need lazy loading. Inherit your class from it and then you'd have two methods you can override (can't remember their names). First one is called each time any page is requested. Open the session there and put the session in viewstate. The other method is called when page is posted back, close your session there.

Sheraz
A: 

You should use a shrinkwrapped package for dealing with this.

I like to use Autofac with ASP.NET/MVC integration. You simply ask the RequestContainer for an ISession whenever you need it and, because the ISession is IDisposable, the RequestContainer automatically knows to dispose of the ISession when the current request ends. Everything is taken care of for you.

Justice
+1  A: 

I just had a 'palm slaps forehead' moment. Despite the fact that I am in fact deploying to an IIS 7 server, I have been debugging using the VS 2008 Built in Web server (Casini). Casini passes all requests through the ASP.NET pipeline, IIS does not. This was causing a request for an image file or javascript file (or any other static resource) to close my NHibernate session before I was actually thinking it should close.

Thanks for the list of resources, I will certainly look into them.

NerdFury
Soooo...how'd you fix it then? Getting the same error.
rball
me too.. transfering from iis 6 to iis 7 caused simular problem for me
Johan Wikström
found my issue. I needed to add a httpModule in the webconfig. Using IIS6 and the built in cassini this wasent needed.
Johan Wikström