using Serilog; using SqlSugar; using System.Text.RegularExpressions; using Yitter.IdGenerator; using YuanXuan.IM.Common.Configs; using YuanXuan.IM.Infrastructure.DBContext; namespace YuanXuan.IM.Api.CollectionExtensions { public static class SqlSugarServiceCollectionExtensions { /// /// 添加SqlSugar /// /// /// /// public static IServiceCollection AddSqlSugar(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env) { var connectionStrings = configuration.GetSection("ConnectionStrings").Get(); //YitIdHelper.SetIdGenerator(new IdGeneratorOptions(configuration.GetValue("SnowFlakeWorkId"))); // 自定义雪花ID算法 程序启动时执行一次就行 StaticConfig.CustomSnowFlakeFunc = () => { return YitIdHelper.NextId(); }; services.AddScoped(provider => { var serviceProvider = provider; // 获取 IServiceProvider List configs = new() { new ConnectionConfig { DbType = DbType.MySql, ConfigId = nameof(connectionStrings.Db), ConnectionString = connectionStrings?.Db ?? throw new InvalidOperationException("Connection string cannot be null."), IsAutoCloseConnection = true, AopEvents = SetAopEvents(connectionStrings.Db, env.EnvironmentName, serviceProvider), }, new ConnectionConfig { DbType = DbType.MySql, ConfigId = nameof(connectionStrings.UserCenterDb), ConnectionString = connectionStrings?.UserCenterDb ?? throw new InvalidOperationException("Connection string cannot be null."), IsAutoCloseConnection = true, AopEvents = SetAopEvents(connectionStrings.UserCenterDb, env.EnvironmentName, serviceProvider), } }; return new SqlSugarClient(configs); }); services.AddScoped(typeof(SugarRepository<>)); return services; } private static AopEvents SetAopEvents(string connectionString, string environmentName, IServiceProvider serviceProvider) { var aopEvents = new AopEvents(); if (environmentName == Environments.Development) { // 正则表达式匹配Ip var ipMatch = Regex.Match(connectionString, @"((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))"); var connections = connectionString.Split(';'); string dbNamne = string.Empty; foreach (var item in connections) { if (item.Contains("Database")) { dbNamne = item.Split('=')[1]; } } aopEvents.OnLogExecuting = (sql, pars) => { // 打印 Sql 语句 Console.WriteLine($"执行Sql:{Environment.NewLine}{UtilMethods.GetNativeSql(sql, pars)}"); Log.Logger.Debug($"执行Sql:{Environment.NewLine}{UtilMethods.GetNativeSql(sql, pars)}"); }; } //aopEvents.DataExecuting += (oldValue, entityInfo) => //{ // // 获取 ICurrentUserService // var currentUserService = serviceProvider.GetService(); // //if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityValue is BaseEntity baseEntity) // //{ // // if (entityInfo.OperationType == DataFilterType.InsertByObject) // // { // // // 插入时填充创建信息 // // baseEntity.CreatedUserId = currentUserService.GetUserId(); // // baseEntity.CreatedUserName = currentUserService.GetUserName(); // // baseEntity.CreatedUserRealname = currentUserService.GetUserName(); // // } // // else if (entityInfo.OperationType == DataFilterType.UpdateByObject) // // { // // // 更新时填充修改信息 // // baseEntity.ModifiedUserId = currentUserService.GetUserId(); // // baseEntity.ModifiedUserName = currentUserService.GetUserName(); // // baseEntity.ModifiedUserRealname = currentUserService.GetUserName(); // // } // //} //}; return aopEvents; } } }