tags:

views:

139

answers:

4

I attended Udi Dahan's lecture at ndc 2009 in Norway - Making Patterns Complete. Now I want to replace my all my repositories with MessageHandlers in Nservicebus. I am using Nhibernate, but I don't know where to put BeginTranscactin/commit and OpenSession. Should each messagehandler contain begintransaction and openSession ?
What about a pipeline of Messages that are running in a synchronized manner ?
And I guess it's not possible to open the session outside of the message and pass it as a property on the message - since the caller and the server are running in two different processes.

Example of messagehandlers:

IGetOrderHeaders , returns order without orderlines
IGetOrderWithOrderlines , returns order with orderlines
ITakeOrderByTruck, the current truck aquires the order from the pool
IUnloadPalletFromCarByTruck, unloads a pallet from a car
IPutPalletAtLocationByTruck, place a pallet at location
IMakeOrderDoneByTruck, sets the orderstatus to done by current truck

I have also considered using Prism serverside instead of nservicebus - this works actually quite good, though it's not intented to use it serverside. But the ideal solution would be nservicebus.

+2  A: 

You do this by implementing a messagemodule (IMessageModule). Take a look at the NHibernateMessageModule that is used by the NHibernate saga persister:

trunk\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate

You can either cache the session in the sessionfactory (like the sample above) or store it in your favorite container using its "ThreadStatic" cache mode.

NServiceBus runs all handlers in a TransactionScope so that will take care of the transaction for you automatically!

Hope this helps!

Andreas
ThreadStatic will use one session for one thread, so it will use a very long living session, and will be in memory during the whole application. This causes memory issues when the session is not cleared manually, and makes it unusable. Or am I wrong?
Paco
IFAIK the NHibernate integration with System.Transactions will close and dispose the session when it commits/aborts so that will take care of releasing any resources that the session holds.
Andreas
It does commit, but it doesn't dispose.
Paco
A: 

Andreas, Could you please give a sample of two nested messagehandlers that uses transactionscope and where to inject/setup sessionfactory. I am really new to nvservicebus..

Lars-Erik
+1  A: 

I've blogged about this a while ago:

http://andreasohlund.blogspot.com/2010/02/nhibernate-session-management-in.html

Does this help?

Andreas
A: 

Great. Nice article.

larserik