-
Notifications
You must be signed in to change notification settings - Fork 0
/
TransactionalAttribute.cs
58 lines (49 loc) · 1.73 KB
/
TransactionalAttribute.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Rougamo.Context;
namespace Light.EntityFrameworkCore.Transactional
{
[AttributeUsage(AttributeTargets.Method)]
public class TransactionalAttribute : Rougamo.MoAttribute
{
private static readonly AsyncLocal<DbContext> _dbContext = new();
private static readonly AsyncLocal<DbContextTransactionCounter> _trans = new();
public static void SetServiceProvider(DbContext dbContext) => _dbContext.Value = dbContext;
public override void OnEntry(MethodContext context)
{
ArgumentNullException.ThrowIfNull(_dbContext.Value);
if (_trans.Value != null)
{
_trans.Value.Count++;
return;
}
_trans.Value = new DbContextTransactionCounter()
{
Count = 1, Transaction = _dbContext.Value.Database.BeginTransaction(),
};
}
public override void OnException(MethodContext context)
{
ArgumentNullException.ThrowIfNull(_trans.Value);
_trans.Value.Count--;
if (_trans.Value.Count == 0)
{
_trans.Value.Transaction.Rollback();
}
}
public override void OnSuccess(MethodContext context)
{
ArgumentNullException.ThrowIfNull(_trans.Value);
_trans.Value.Count--;
if (_trans.Value.Count == 0)
{
_trans.Value.Transaction.Commit();
}
}
}
internal class DbContextTransactionCounter
{
public IDbContextTransaction Transaction { get; set; } = null!;
public uint Count { get; set; }
}
}