tags:

views:

150

answers:

5

i have a client server application, the server uses nhibernate. i wanna know how should i use the session? per call? per client? single?

other way?

and how can i keep the session cache in the server ? and also i wanna know if the session is thread safe?

+1  A: 

Per call should be the usual solution

Fredrik Leijon
+6  A: 

You should use one session per unit of work. If that includes multiple operations, so be it.

Use the session.BeginTransaction() to wrap the unit of work and commit once all the items are done.

Sessions are NOT thread safe, but the session factory is (which you definitely want to keep around).

NHiberate has various cache options for data, but the sessions are meant to be used and disposed.

Chris Patterson
is there a way to keep the cache after session disposed?
Chen Kinnrot
Ayende has a few good links on how the caching is implemented in NHibernate. For read-only objects (like lookup tables) you can get a nice benefit if you read them often. Otherwise your concurrency requirements may prevent you from keeping data cached. Its an it depends kind of question. The Ayende article is http://ayende.com/Blog/archive/2009/04/24/nhibernate-2nd-level-cache.aspx
Chris Patterson
+3  A: 

Normally it's done one per request. You can create HttpApplication, which opens the session at the beginning of request and closes at the end of request (example).

Marek Tihkan
+1  A: 

There really is no one right answer to the question of session lifetime. You can make any session lifetime work, it depends on your requirements. Sessions are not thread safe, but session factories are.

To keep the cache around, you need to keep the session around. It is likely to be fairly challenging to keep the cache around and keep the cache correct in anything but simple single user, single process applications.

Michael Maddox
+1  A: 

There's a great example I've used from NHibernate Best Practices.

The code example uses a session per ASP.NET request.

Dead account