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