刘磊
2025-06-09 dabbcafc629ef87d11ba55ef8cc1cdc776c047d8
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
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.AOP;
using WIDESEA_Core.DB;
using WIDESEA_Core.Helper;
using WIDESEA_Core.LogHelper;
using WIDESEA_Core.Seed;
 
namespace WIDESEA_Core
{
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlsugarSetup
    {
        private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
 
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
 
            // 默认添加主数据库连接
            //MainDb.CurrentDbConnId = AppSettings.app(new string[] { "MainDB" });
 
            // SqlSugarScope是线程安全,可使用单例注入
            // 参考:https://www.donet5.com/Home/Doc?typeId=1181
            services.AddScoped<ISqlSugarClient>(o =>
            {
                var memoryCache = o.GetRequiredService<IMemoryCache>();
 
                // 连接字符串
                var listConfig = new List<ConnectionConfig>
                {
                    new ConnectionConfig
                    {
                        ConfigId = MainDb.CurrentDbConnId,
                        ConnectionString = DBContext.GetMainConnectionDb().Connection,
                        IsAutoCloseConnection = true,
                        DbType = MainDb.DbType,
                        AopEvents = new AopEvents
                        {
                            OnLogExecuting = (sql, p) =>
                            {
                                  Parallel.For(0, 1, e =>
                                  {
                                        MiniProfiler.Current.CustomTiming("SQL:", GetParas(p) + "【SQL语句】:" + sql);
                                  });
                            }
                        }
                    }
                };
                #region 从库
                //var listConfig_Slave = new List<SlaveConnectionConfig>();
                //BaseDBConfig.MutiConnectionString.ForEach(s =>
                //{
                //    if(s.ConnId != MainDb.CurrentDbConnId)
                //    {
                //        listConfig_Slave.Add(new SlaveConnectionConfig()
                //        {
                //            HitRate = s.HitRate,
                //            ConnectionString = s.Connection
                //        });
                //    }
 
                //});
 
                //BaseDBConfig.MutiConnectionString.ForEach(m =>
                //{
                //    listConfig.Add(new ConnectionConfig()
                //    {
                //        ConfigId = m.ConnId.ObjToString().ToLower(),
                //        ConnectionString = m.Connection,
                //        DbType = (DbType)m.DbType,
                //        IsAutoCloseConnection = true,
                //        MoreSettings = new ConnMoreSettings()
                //        {
                //            //IsWithNoLockQuery = true,
                //            IsAutoRemoveDataCache = true
                //        },
                //        // 从库
                //        //SlaveConnectionConfigs = listConfig_Slave,
                //        // 自定义特性
                //        ConfigureExternalServices = new ConfigureExternalServices()
                //        {
                //            DataInfoCacheService = new SqlSugarMemoryCacheService(memoryCache),
                //            EntityService = (property, column) =>
                //            {
                //                if (column.IsPrimarykey && property.PropertyType == typeof(int))
                //                {
                //                    column.IsIdentity = true;
                //                }
                //            }
                //        },
                //        InitKeyType = InitKeyType.Attribute,
                //        AopEvents = new AopEvents()
                //        {
                //            OnError = x =>
                //            {
                //                Console.WriteLine(x.Sql);
                //            }
                //        }
                //    }
                //   );
                //});
                #endregion
 
                SqlSugarClient sqlSugarClient = new SqlSugarClient(listConfig, db =>
                {
                    db.Aop.DataExecuting = SqlSugarAop.DataExecuting;
                });
                return sqlSugarClient;
            });
        }
 
        private static string GetWholeSql(SugarParameter[] paramArr, string sql)
        {
            foreach (var param in paramArr)
            {
                sql.Replace(param.ParameterName, param.Value.ObjToString());
            }
 
            return sql;
        }
 
        private static string GetParas(SugarParameter[] pars)
        {
            string key = "【SQL参数】:";
            foreach (var param in pars)
            {
                key += $"{param.ParameterName}:{param.Value}\n";
            }
 
            return key;
        }
    }
}