.nettransactionssystem.transactions

Execute code only if parent transaction completes


The code below will output:

Event published
Command executed

Using System.Transactions how can I have the EventPublisher enlist in a parent transaction such that it only executes if the CommandHandler completes. The output would therefore be:

Command executed
Event published

Code:

class Program
    {
        static void Main(string[] args)
        {           
            var handler = new CommandHandler();
            handler.Execute();

            Console.ReadLine();
        }
    }

    public class CommandHandler
    {
        public void Execute()
        {
            var foo = new Foo();
            foo.DoSomething();

            Console.WriteLine("Command executed");
        }
    }

    public class EventPublisher
    {
        public void PublishEvent()
        {
            Console.WriteLine("Event published");
        }
    }
public class Foo
{
    public void DoSomething()
    {
        new EventPublisher().PublishEvent();
    }
}

Solution

  • The solution was actually to enlist in the transaction by implementing IEnlistmentNotification.