views:

997

answers:

1

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.

+4  A: 

If you mark your endpoint as transaction (.MsmqTransport().IsTransactional(true) or just AsA_Server) then the transactions will enlist into the one NServiceBus opened. What this means is that the commits you have inside your handler won't actually happen and the whole thing will either commit or rollback together - unless you specifically tell your transactions not to enlist in the ambient transaction.

Whether or not you work directly with the session or through a UoW, it looks like you want to do more than one for a given message - why? The message is already the natural UoW.

Udi Dahan