What is the recommended lifespan of a message handler?
My current implementation is raising a few problems, especially when it comes to data access (NHibernate).
Our current implementation is as follows:
Client Application (web)
Sends messages to a queue (in memory, msmq, azure)
Worker application (windows service)
Polls the queues, and passes the messages to the registered handlers.
When we initialize the worker, we register our handlers. The handlers are lazily loaded (using Lazy<T>
) so they are not created until the queue processor actually starts (on a different thread).
When the handlers are initialized, we fill out their dependencies and they sit in memory until the queue processor is shut down.
One issue we have is that we are now using a single NHibernate ISession for all the handlers on a queue processor. It seems that a better solution would be to recreate the handlers on each cycle of the queue processor, meaning that each handler can have it's own ISession.
What is the recommended approach?
Since the handler is directly tied to the operation of handling a message their lifetime should be the same.
If you use some kind of unit of work (NHibernate ISession) it's probably best to have one per transport message as xelibrion sais. One transport message could contain more logical (application) messages which should be processed together if they arrived in the same physical message.
This is the way it's done in NServiceBus and NanoMessageBus.