-
Notifications
You must be signed in to change notification settings - Fork 652
/
TransactionScopeUnitOfWorkBehavior.cs
43 lines (37 loc) · 1.58 KB
/
TransactionScopeUnitOfWorkBehavior.cs
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
namespace NServiceBus
{
using System;
using System.Threading.Tasks;
using System.Transactions;
using Pipeline;
class TransactionScopeUnitOfWorkBehavior : IBehavior<IIncomingPhysicalMessageContext, IIncomingPhysicalMessageContext>
{
public TransactionScopeUnitOfWorkBehavior(TransactionOptions transactionOptions)
{
this.transactionOptions = transactionOptions;
}
public async Task Invoke(IIncomingPhysicalMessageContext context, Func<IIncomingPhysicalMessageContext, Task> next)
{
if (Transaction.Current != null)
{
throw new Exception("Ambient transaction detected. The transaction scope unit of work is not supported when there already is a scope present.");
}
using (var tx = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled))
{
await next(context).ConfigureAwait(false);
tx.Complete();
}
}
readonly TransactionOptions transactionOptions;
public class Registration : RegisterStep
{
public Registration(TransactionOptions transactionOptions) : base("HandlerTransactionScopeWrapper",
typeof(TransactionScopeUnitOfWorkBehavior),
"Makes sure that the handlers gets wrapped in a transaction scope",
b => new TransactionScopeUnitOfWorkBehavior(transactionOptions))
{
InsertAfter("ExecuteUnitOfWork");
}
}
}
}