Mark Struzinski
Mark Struzinski

Reputation: 33471

Best way to manage session in NHibernate?

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?

Upvotes: 5

Views: 6704

Answers (4)

huseyint
huseyint

Reputation: 15081

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

Upvotes: 0

Chris Conway
Chris Conway

Reputation: 16519

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

Upvotes: 2

Ben Scheirman
Ben Scheirman

Reputation: 40961

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.

Upvotes: 1

Related Questions