下面的代码将输出:
Event published
Command executed
使用 System.Transactions 如何让 EventPublisher 在父事务中登记,以便它仅在 CommandHandler 完成时执行。因此,输出将是:
Command executed
Event published
代码:
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();
}
}