I have WCF services hosted as http endpoints in IIS. At some points in the handling of command requests to these services, I want to publish an event on NServiceBus to indicate what command was processed. Is it possible for me to do that within a TransactionScope that I create and manage in my code (so that I can include my database interactions in the same transaction)? I would want to be able to publish from the bus within that scope, such that the publication actually goes through if the scope is completed. When I run the following:
using (var scope = new TransactionScope()) {
bus.Publish(new SomethingHappened { Description = String.Format("{0} logged in at {1}", user.Name, DateTime.Now.ToLongTimeString()) }).ConfigureAwait(false).GetAwaiter().GetResult();
}
I find that the message is received by subscribers, even though I did not call scope.Complete()
on the transaction scope. What, if anything, can I change so that the publish is enrolled in the scope?
It turns out that in order for the transaction scope to manage the async call, you need to open it with the special option TransactionScopeAsyncFlowOption.Enabled
like so:
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
bus.Publish(new SomethingHappened { Description = String.Format("{0} logged in at {1}", user.Name, DateTime.Now.ToLongTimeString()) }).ConfigureAwait(false).GetAwaiter().GetResult();
}
Doing that, you get the behavior I was expecting.