Chen Kinnrot
Chen Kinnrot

Reputation: 21015

Correct use of nhibernate session

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?

Upvotes: 0

Views: 433

Answers (5)

Dead account
Dead account

Reputation: 19960

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

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

Upvotes: 1

Michael Maddox
Michael Maddox

Reputation: 12489

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.

Upvotes: 1

Marek Tihkan
Marek Tihkan

Reputation: 1914

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).

Upvotes: 3

Chris Patterson
Chris Patterson

Reputation: 33288

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.

Upvotes: 7

Fredrik Leijon
Fredrik Leijon

Reputation: 2802

Per call should be the usual solution

Upvotes: 1

Related Questions