Search code examples
.nettransactionsrollbackdistributed-transactionsservicedcomponent

How to Detect a Transaction Abort in a ServicedComponent?


I'm trying to create a System.EnterpriseServices.ServicedComponent in order to participate in a distributed transaction. My main method looks something like this:

public void DoSomething()
{
    try
    {
      // do something useful

      // vote for commit

      if (ContextUtil.IsInTransaction)
          ContextUtil.MyTransactionVote = TransactionVote.Commit;
    }

    catch
    {
      // or shoud I use ContextUtil.SetAbort() instead?

      if (ContextUtil.IsInTransaction)
          ContextUtil.MyTransactionVote = TransactionVote.Abort;

      throw;
    }
}

What I'm trying to do is detecting whether the distributed transaction has been aborted (or rolled back) and then proceed to rollback my changes as well. For instance, I might have created a file on disk, or done some side effects that need to be undone.

I have tried to handle the SystemTransaction.TransactionCompleted event or inspected the state of the SystemTransaction in the Dispose() method without success.

I understand that this is similar to "compensation" rather than "transaction".

Does what I'm trying to do even make sense ?


Solution

  • Answering my own question, this is possible by deriving the ServicedComponent from System.Transactions.IEnlistmentNotification as well.