views:

1112

answers:

5

I'm new to NHibernate (my 1st big project with it). I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. This doesn't work in a situation where lazy-loading is required, however. For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception. Anyone using a different method?

A: 

Keep your session open for your entire unit of work. If your session is life is too small, you cannot benefit from the session level cache (which is significant). Any time you can prevent a roundtrip to the database is going to save a lot of time. You also cannot take advantage of lazy loading, which is crucial to understand.

If your session lifetime is too big, you can run into other issues.

If this is a web app, you'll probably do fine with the session-per-httpRequest pattern. Basically this is an HttpModule that opens the session at the beginning of the request and flushes/closes at the end. Be sure to store the session in HttpContext.Items NOT A STATIC VARIABLE. <--- leads to all kinds of problems that you don't want to deal with.

You might also look at RhinoCommons for a unit of work implementation.

Ben Scheirman
+2  A: 

check out the SummerOfNHibernate webcasts for a great tutorial... What you're looking for specifically doesn't come until webisode 5 or 6.

Chris Conway
A: 

Ben, I am developing a web app. Do you have any examples of the Session per HttpRequest pattern? I'm googling around for it now, but not much luck so far.

Chris, I have been keeping up w/ the Summer of NHibernate screencasts, but he's not addressing session management in a web app until session 13 or so, which is mid-Sept. So far, he has done session management using a static variable in a test class.

Mark Struzinski
+5  A: 

Session management:

http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/HybridSessionBuilder.cs

Session per request:

http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/NHibernateSessionModule.cs

Matt Hinze
Just a note, some months later. While we're still using the approaches above, for the most part, there is more interesting work done by the folks working on using an IOC tool to manage `ISessions` and `ISessionFactory`s - might want to check out the StructureMap and FubuMvc projects for more info.
Matt Hinze
@Matt: take a look at the Castle NHibernate facility, it's been around for years: http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html
Mauricio Scheffer
A: 

Since you are developing a Web App (presumably with ASP.NET), check out NHibernate Best Practices with ASP.NET at CodeProject.

huseyint