views:

159

answers:

2

Hi,

I've created a windows service which is listening to a MSMQ. For each message I receive, some DB transactions need to be made. Later it might be possible that there will be 1 message every second. Currently the Nhib session is kept open until the service is stopped manually. Is it a good practice or should I close the session after each message?

Thanks in advance

A: 

In contrast to the session factory (ISessionFactory) which is thread safe you should open and close the session (ISession) with every database transaction.

Darin Dimitrov
+3  A: 

An NHibernate session is meant to be relatively short lived, so its generally not a good idea to keep it active for a longer period. The session caches entities and as more entities are fetched more data is cached, if you don't manage the caching in some way. This leads to a performance degradation.

The NHibernate docs describe ISession like this:

A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps an ADO.NET connection. Factory for ITransaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

I would suggest using a session-per-conversation, i.e. if you have a few db operations that "belong together" you use the same session for those operations, but when those operations are done you close the session.

So, using a new session for each message you process sounds like a good idea.

Erik Öjebo