-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransactionsExample.cs
More file actions
45 lines (38 loc) · 1.73 KB
/
Copy pathTransactionsExample.cs
File metadata and controls
45 lines (38 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Codefinity.EventEmitter.Sample.Infrastructure;
using Codefinity.EventEmitter.Sample.Inventory;
using Codefinity.EventEmitter.Sample.Orders;
using Codefinity.EventEmitter.Sample.Shipping;
using Microsoft.Extensions.DependencyInjection;
namespace Codefinity.EventEmitter.Sample.Examples;
/// <summary>
/// OrderService publishes inside a TransactionScope. Module listeners run only if it commits.
/// </summary>
internal static class TransactionsExample
{
public static async Task RunAsync()
{
await using var app = await ExampleApp.StartAsync(services => services
.AddOrdersModule()
.AddInventoryModule()
.AddShippingModule());
var carrier = app.Get<CarrierGateway>();
app.Say("order-1 commits:");
await app.InScopeAsync(sp => sp.GetRequiredService<OrderService>().CompleteAsync("order-1", "alice"));
await app.WaitUntilAsync(() => carrier.Shipments.ContainsKey("order-1"));
app.Say("order-2 publishes OrderCompleted, then payment fails and the transaction rolls back:");
try
{
await app.InScopeAsync(sp => sp.GetRequiredService<OrderService>()
.CompleteAsync("order-2", "bob", failBeforeCommit: true));
}
catch (InvalidOperationException ex)
{
app.Say($"Caught: {ex.Message}");
}
await Task.Delay(300);
var incomplete = await app.Get<IIncompleteEventPublications>().FindAllAsync();
app.Say("Inventory and Shipping never heard about order-2:");
app.Say($" shipment for order-2: {(carrier.Shipments.ContainsKey("order-2") ? "yes" : "none")}");
app.Say($" publications left waiting: {incomplete.Count} (the rollback deleted them)");
}
}