-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTransactionMiddleware.cs
More file actions
50 lines (38 loc) · 1.46 KB
/
TransactionMiddleware.cs
File metadata and controls
50 lines (38 loc) · 1.46 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
46
47
48
49
50
using System.Data;
using ConsoleSample.Messages;
using Foundatio.Mediator;
using Microsoft.Extensions.Logging;
namespace ConsoleSample.Middleware;
public class TransactionMiddleware
{
public IDbTransaction Before(CreateOrder cmd, ILogger<TransactionMiddleware> logger)
{
var transaction = new FakeTransaction();
logger.LogInformation("Transaction started: {TransactionId}", transaction.Id);
return transaction;
}
public void After(CreateOrder cmd, IDbTransaction transaction, ILogger<TransactionMiddleware> logger)
{
var tx = (FakeTransaction)transaction;
transaction.Commit();
logger.LogInformation("Transaction committed: {TransactionId}", tx.Id);
}
public void Finally(CreateOrder cmd, Result? result, IDbTransaction? transaction, ILogger<TransactionMiddleware> logger)
{
if (transaction is not FakeTransaction tx)
return;
if (result?.IsSuccess == true)
return;
logger.LogInformation("Transaction rolled back: {TransactionId}", tx.Id);
transaction.Rollback();
}
}
public class FakeTransaction : IDbTransaction
{
public string Id { get; } = Guid.NewGuid().ToString("N").Substring(0, 8);
public IDbConnection? Connection => throw new NotImplementedException();
public IsolationLevel IsolationLevel => throw new NotImplementedException();
public void Commit() { }
public void Dispose() { }
public void Rollback() { }
}