NServiceBus and NHibernate - Message Handler and Transactions

Posted by mattcodes on Stack Overflow See other posts from Stack Overflow or by mattcodes
Published on 2009-10-17T10:36:16Z Indexed on 2010/03/08 5:06 UTC
Read the original article Hit count: 1476

From my understanding NServiceBus executes the Handle method of an IMessageHandler within a transaction, if an exception propagates out of this method, then NServiceBus will ensure the message is put back on the message queue (up X amount of times before error queue) etc.. so we have an atomic operation so to speak.

Now when if I inside my NServiceBus Message Handle method I do something like this

using(var trans = session.BeginTransaction())
{ 

  person.Age = 10;
  session.Update<Person>(person);
  trans.Commit()
}

using(var trans2 = session.BeginTransaction())
{ 

  person.Age = 20;
  session.Update<Person>(person);
  // throw new ApplicationException("Oh no");
  trans2.Commit()
}

What is the effect of this on the transaction scope? Is trans1 now counted as a nested transaction in terms of its relationship with the Nservicebus transaction even though we have done nothing to marry them up? (if not how would one link onto the transaction of NServiceBus?

Looking at the second block (trans2), if I uncomment the throw statement, will the NServiceBus transaction then rollback trans1 as well? In basic scenarios, say I dump the above into a console app, then trans1 is independent, commit, flushed and won't rollback. I'm trying to clarify what happens now we sit in someone else's transaction like NServiceBus?

The above is just example code, im wouldnt be working directly with session, more like through a uow pattern.

© Stack Overflow or respective owner

Related posts about nservicebus

Related posts about nhibernate