z8018
2 天以前 d8dc91f9c1fece5711e38edd1b1274cb9e579015
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Helper;
 
namespace WIDESEA_Core.BaseRepository
{
    public class UnitOfWorkManage : IUnitOfWorkManage
    {
        // 定义日志记录器
        private readonly ILogger<UnitOfWorkManage> _logger;
        // 定义SqlSugarClient
        private readonly ISqlSugarClient _sqlSugarClient;
 
        // 定义事务计数器
        private int _tranCount { get; set; }
        // 定义事务计数器的只读属性
        public int TranCount => _tranCount;
        // 定义事务栈
        public readonly ConcurrentStack<string> TranStack = new();
 
        // 构造函数,初始化日志记录器和SqlSugarClient
        public UnitOfWorkManage(ISqlSugarClient sqlSugarClient, ILogger<UnitOfWorkManage> logger)
        {
            _sqlSugarClient = sqlSugarClient;
            _logger = logger;
            _tranCount = 0;
        }
 
        /// <summary>
        /// 获取DB,保证唯一性
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetDbClient()
        {
            // 必须要as,后边会用到切换数据库操作
            return _sqlSugarClient as SqlSugarClient;
        }
 
 
        // 创建UnitOfWork
        public UnitOfWork CreateUnitOfWork()
        {
            UnitOfWork uow = new UnitOfWork();
            uow.Logger = _logger;
            uow.Db = _sqlSugarClient;
            uow.Tenant = (ITenant)_sqlSugarClient;
            uow.IsTran = true;
 
            uow.Db.Open();
            uow.Tenant.BeginTran();
            
            _logger.LogDebug("UnitOfWork Begin");
            return uow;
        }
 
        // 开始事务
        public void BeginTran()
        {
            lock (this)
            {
                _tranCount++;
                GetDbClient().BeginTran();
            }
        }
 
        // 开始事务,并记录方法名
        public void BeginTran(MethodInfo method)
        {
            lock (this)
            {
                GetDbClient().BeginTran();
                TranStack.Push(method.GetFullName());
                _tranCount = TranStack.Count;
            }
        }
 
        // 开始事务,并执行函数,根据函数返回值决定是否提交事务
        public WebResponseContent BeginTran(Func<WebResponseContent> func)
        {
            lock (this)
            {
                BeginTran();
                try
                {
                    WebResponseContent content = func();
                    if (content.Status)
                    {
                        CommitTran();
                    }
                    else
                    {
                        RollbackTran();
                    }
                    return content;
                }
                catch(Exception ex)
                {
                    RollbackTran();
                    return WebResponseContent.Instance.Error(ex.Message);
                }
            }
        }
 
        // 提交事务
        public void CommitTran()
        {
            lock (this)
            {
                _tranCount--;
                if (_tranCount == 0)
                {
                    try
                    {
                        GetDbClient().CommitTran();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        GetDbClient().RollbackTran();
                    }
                }
            }
        }
 
        // 提交事务,并记录方法名
        public void CommitTran(MethodInfo method)
        {
            lock (this)
            {
                string result = "";
                while (!TranStack.IsEmpty && !TranStack.TryPeek(out result))
                {
                    Thread.Sleep(1);
                }
 
 
                if (result == method.GetFullName())
                {
                    try
                    {
                        GetDbClient().CommitTran();
 
                        _logger.LogDebug($"Commit Transaction");
                        Console.WriteLine($"Commit Transaction");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        GetDbClient().RollbackTran();
                        _logger.LogDebug($"Commit Error , Rollback Transaction");
                    }
                    finally
                    {
                        while (!TranStack.TryPop(out _))
                        {
                            Thread.Sleep(1);
                        }
 
                        _tranCount = TranStack.Count;
                    }
                }
            }
        }
 
        // 回滚事务
        public void RollbackTran()
        {
            lock (this)
            {
                _tranCount--;
                GetDbClient().RollbackTran();
            }
        }
 
        // 回滚事务,并记录方法名
        public void RollbackTran(MethodInfo method)
        {
            lock (this)
            {
                string result = "";
                while (!TranStack.IsEmpty && !TranStack.TryPeek(out result))
                {
                    Thread.Sleep(1);
                }
 
                if (result == method.GetFullName())
                {
                    GetDbClient().RollbackTran();
                    _logger.LogDebug($"Rollback Transaction");
                    Console.WriteLine($"Rollback Transaction");
                    while (!TranStack.TryPop(out _))
                    {
                        Thread.Sleep(1);
                    }
 
                    _tranCount = TranStack.Count;
                }
            }
        }
    }
}