1
dengjunjie
2025-02-18 b2ad000e07e1c87d3561b5aa94fdc88c779872f0
ÏîÄ¿´úÂë/WMS/WIDESEA_WMSServer/WIDESEA_Core/Extensions/SqlsugarSetup.cs
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,145 @@
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);
                                      //Console.Out.WriteLine(sql);
                                      //Console.Out.WriteLine();
                                  });
                            }
                        }
                    }
                };
                #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;
        }
    }
}