/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="appSettings"></param> /// <returns></returns> public static IServiceCollection AddDb(this IServiceCollection services, AppSettings appSettings) { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(appSettings.Db.Type, appSettings.Db.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); var fsql = freeSqlBuilder.Build(); services.AddFreeRepository(filter => filter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false)); services.AddScoped <UnitOfWorkManager>(); services.AddSingleton(fsql); if (appSettings.Db.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion return(services); }
/// <summary> /// 创建FreeSql实例 /// </summary> /// <param name="user"></param> /// <param name="appConfig"></param> /// <param name="dbConfig"></param> /// <param name="tenant"></param> /// <returns></returns> private static IFreeSql CreateFreeSql(IUser user, AppConfig appConfig, DbConfig dbConfig, CreateFreeSqlTenantDto tenant) { var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(tenant.DbType.Value, tenant.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion 监听所有命令 var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //配置实体 DbHelper.ConfigEntity(fsql, appConfig); #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion 监听Curd操作 #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); fsql.Aop.AuditValue += (s, e) => { DbHelper.AuditValue(e, timeOffset, user); }; #endregion 审计数据 return(fsql); }
/// <summary> /// 增加 FreeSql 数据库操作服务 /// </summary> /// <param name="services"></param> /// <param name="optionsAction"></param> /// <param name="configureAction"></param> /// <returns></returns> public static IServiceCollection AddFreeSql(this IServiceCollection services, Action <FreeSqlBuilder> optionsAction, Action <IFreeSql>?configureAction = null) { services.AddSingleton <IFreeSql>(sp => { var builder = new FreeSqlBuilder(); optionsAction(builder); var instance = builder.Build(); configureAction?.Invoke(instance); return(instance); }); services.AddSingleton(typeof(IDataService <>), typeof(DefaultDataService <>)); return(services); }
public static void AddFreeSql(this IServiceCollection service) { var freeSql = service.BuildServiceProvider().GetRequiredService <IOptions <FreeSqlConfig> >().Value; //注入FreeSql service.AddSingleton <IFreeSql>(f => { var log = f.GetRequiredService <ILogger <IFreeSql> >(); var freeBuilder = new FreeSqlBuilder() .UseAutoSyncStructure(true) .UseConnectionString(freeSql.DataType, freeSql.MasterConnetion) .UseLazyLoading(true) .UseMonitorCommand( executing => { //执行中打印日志 log.LogInformation(executing.CommandText); } // null, //(executed, t) => //{ // //执行后打印日志 // log.LogWarning(t); //} ) .UseCache(null); if (freeSql.SlaveConnections?.Count > 0)//判断是否存在从库 { freeBuilder.UseSlave(freeSql.SlaveConnections.Select(x => x.ConnectionString).ToArray()); } var freesql = freeBuilder.Build(); //我这里禁用了导航属性联级插入的功能 freesql.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = false); return(freesql); }); //注入Uow service.AddScoped <IRepositoryUnitOfWork>(f => f.GetRequiredService <IFreeSql>().CreateUnitOfWork()); //注入HttpContextAccessor 可以从IOC中拿到HttpContext的内容 service.AddHttpContextAccessor(); service.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>(); //注入当前用户 利用了缓存查询当前用户信息 service.AddScoped <CurrentUser>(f => f.GetRequiredService <IHttpContextAccessor>().HttpContext?.User?.GetCurrentUser(f)); //使用类库Scrutor做发现注入类库和服务 service.AddServer(typeof(IRepKey)); service.AddServer(typeof(IDomainBase)); //Automapper和配置模板 注入 service.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); }
/// <summary> /// 注册MySql工作单元服务 /// </summary> /// <typeparam name="TUnitOfWOrk">工作单元接口类型</typeparam> /// <typeparam name="TUnitOfWorkImplementation">工作单元实现类型</typeparam> /// <param name="services">服务集合</param> /// <param name="connection">连接字符串</param> /// <param name="setupAction">配置操作</param> public static IServiceCollection AddMySqlUnitOfWork <TUnitOfWOrk, TUnitOfWorkImplementation>(this IServiceCollection services, string connection, Action <FreeSqlBuilder> setupAction = null) where TUnitOfWOrk : class, IUnitOfWork where TUnitOfWorkImplementation : UnitOfWorkBase, TUnitOfWOrk { var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(DataType.MySql, connection) .UseLazyLoading(false); setupAction?.Invoke(freeSqlBuilder); var freeSql = freeSqlBuilder.Build(); freeSql.GlobalFilter.Apply <ISoftDelete>("SoftDelete", x => x.IsDeleted == false); services.AddSingleton <IFreeSql>(freeSql); services.AddScoped <TUnitOfWOrk, TUnitOfWorkImplementation>(); return(services); }
/// <summary> /// 添加数据库上下文 /// </summary> /// <param name="services">服务集合</param> /// <param name="configure">配置</param> /// <returns>服务集合</returns> public static IServiceCollection AddDatabaseAccessor(this IServiceCollection services, Action <IServiceCollection> configure = null) { services.AddConfigurableOptions <DatabaseAccessorSettingsOptions>(); var dbConfig = App.GetDefultOptions <DatabaseAccessorSettingsOptions>(); var connectionString = $"Data Source={dbConfig.Host};Port={dbConfig.Port};{$"User ID={dbConfig.User};".IF(dbConfig.User.NotNull())}{$"Password={dbConfig.Password};".IF(dbConfig.Password.NotNull())} Initial Catalog={dbConfig.Database};{dbConfig.Extension}"; var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, connectionString) # if DEBUG .UseAutoSyncStructure(dbConfig.SyncStructure) # endif .UseLazyLoading(false) .UseNoneCommandParameter(true); var fsql = freeSqlBuilder.Build(); if (dbConfig.GlobalFilter) { //全局过滤 fsql.GlobalFilter.Apply <ISoftDeletable>("DeleteTime", a => !a.DeleteTime.HasValue); } #if DEBUG if (dbConfig.PrintingSQL) { //监听生成的sql语句 fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine(e.Sql); }; } if (dbConfig.ReturnCreateSql) { var entities = App.CanBeScanTypes.Where(o => o.IsEntityType()); Console.WriteLine(fsql.CodeFirst.GetComparisonDDLStatements(entities.ToArray())); } #endif services.TryAddScoped <QingShan.Permission.IUserInfo, QingShan.Permission.UserInfo>(); // 注册FreeSql IFreeSql必须使用单例注入 services.AddSingleton <IFreeSql>(fsql); services.TryAddScoped(typeof(IRepository <>), typeof(Repository <>)); // 注册仓储 services.TryAddScoped(typeof(IKeyRepository <,>), typeof(KeyRepository <,>)); services.AddScoped <UnitOfWorkManager>(); configure?.Invoke(services); return(services); }
/// <summary> /// 添加数据库服务 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public async static Task AddDb(this IServiceCollection services, IHostEnvironment env) { var dbConfig = new ConfigHelper().Get <DbConfig>("DbConfig", env.EnvironmentName); var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure) .UseLazyLoading(false) .UseNoneCommandParameter(true); var fsql = freeSqlBuilder.Build(); //fsql.GlobalFilter.Apply<IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //services.AddFreeRepository(filter => filter.Apply<IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false)); services.AddScoped <UnitOfWorkManager>(); services.AddSingleton(fsql); }
public static IFreeSql GetInstance(DataType DataType, string MasterConnetion) { var freeBuilder = new FreeSqlBuilder() .UseConnectionString(DataType, MasterConnetion) .UseLazyLoading(true) .UseMonitorCommand( executing => { //执行中打印日志 //LogDbHelper.Sql(executing.CommandText); // log.LogInformation(executing.CommandText); }); //if (freeSql.SlaveConnections?.Count > 0)//判断是否存在从库 //{ // freeBuilder.UseSlave(freeSql.SlaveConnections.Select(x => x.ConnectionString).ToArray()); //} ////我这里禁用了导航属性联级插入的功能 //freesql.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = false); return(freeBuilder.Build()); }
/// <summary> /// 直接从配置文件读取配置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service"></param> public static void CreateFreeSql <T>(this IServiceCollection service) { service.AddSingleton(f => { var current = f.GetService <FreeSqlCollectionConfig>().FreeSqlConfigs?.FirstOrDefault(x => x.Key == typeof(T).Name) ?? throw new ArgumentNullException(nameof(FreeSqlCollectionConfig), $"appSettings.json文件未检测到{typeof(T).Name}对象"); var builder = new FreeSqlBuilder() .UseConnectionString(current.DataType, current.MasterConnection) .UseAutoSyncStructure(current.IsSyncStructure); if (current.SlaveConnections.Count > 0) { builder.UseSlave(current.SlaveConnections.ToArray()); } var res = builder.Build <T>(); res.Aop.CurdAfter += (s, e) => Aop_CurdAfter(s, e, f.GetService <ILogger <IFreeSql <T> > >()); res.Aop.AuditValue += (s, e) => Aop_Auditer(s, e, f); res.GlobalFilter.Apply <IDeleted>(SysConsts.DELETED_FILTER, x => !x.IsDeleted); res.GlobalFilter.Apply <IEnabled>(SysConsts.ENABLED_FILTER, x => x.Enabled == true); return(res); }); service.AddScoped <IUnitOfWork <T>, UnitOfWork <T> >(); }
/// <summary> /// 添加租户数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public static void AddTenantDb(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); var user = services.BuildServiceProvider().GetService <IUser>(); int idleTime = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10; IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime)); var tenantName = AdminConsts.TenantName; if (appConfig.TenantType == TenantType.Own) { tenantName = "tenant_" + user.TenantId?.ToString(); } ib.TryRegister(tenantName, () => { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //配置实体 DbHelper.ConfigEntity(fsql, appConfig); //共享数据库 if (appConfig.TenantType == TenantType.Share) { fsql.GlobalFilter.ApplyIf <ITenant>("Tenant", () => user.TenantId > 0, a => a.TenantId == user.TenantId); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); fsql.Aop.AuditValue += (s, e) => { DbHelper.AuditValue(e, timeOffset, user); }; #endregion #endregion return(fsql); }); services.AddSingleton(ib); }
/// <summary> /// 添加租户数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public static void AddTenantDb(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); var user = services.BuildServiceProvider().GetService <IUser>(); int idleTime = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10; IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime)); var tenantName = AdminConsts.TenantName; if (appConfig.TenantType == TenantType.Own) { tenantName = "tenant_" + user.TenantId.ToString(); } ib.TryRegister(tenantName, () => { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //配置实体 DbHelper.ConfigEntity(fsql, appConfig); //共享数据库 if (appConfig.TenantType == TenantType.Share) { fsql.GlobalFilter.ApplyIf <ITenant>("Tenant", () => user.TenantId > 0, a => a.TenantId == user.TenantId); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; case "TenantId": e.Value = user.TenantId; break; } if (e.Property.GetCustomAttribute <ServerTimeAttribute>(false) != null && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?)) && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default)) { e.Value = DateTime.Now.Subtract(timeOffset); } }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public async static Task AddDbAsync(this IServiceCollection services, IHostEnvironment env) { var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); //创建数据库 if (dbConfig.CreateDb) { await DbHelper.CreateDatabaseAsync(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); //配置实体 var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); DbHelper.ConfigEntity(fsql, appConfig); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig, appConfig: appConfig); } //同步数据 if (dbConfig.SyncData) { await DbHelper.SyncDataAsync(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonDataAsync(fsql); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 //计算服务器时间 //var serverTime = fsql.Select<T>().Limit(1).First(a => DateTime.local); //var timeOffset = DateTime.UtcNow.Subtract(serverTime); var user = services.BuildServiceProvider().GetService <IUser>(); fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; case "TenantId": e.Value = user.TenantId; break; //case "CreatedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; //case "ModifiedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } }; #endregion #endregion //导入多数据库 if (null != dbConfig.Dbs) { foreach (var multiDb in dbConfig.Dbs) { switch (multiDb.Name) { case nameof(MySqlDb): var mdb = CreateMultiDbBuilder(multiDb).Build <MySqlDb>(); services.AddSingleton(mdb); break; default: break; } } } }
/// <summary> /// 直接从配置文件读取配置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service"></param> public static void AddFreeSql <T>(this IServiceCollection service) { //var thisFontColor = (int)Console.ForegroundColor; //var newFontColor = (ConsoleColor)((thisFontColor + 1) > 15 ? 0 : (thisFontColor + 1)); service.AddSingleton(f => { var log = f.GetRequiredService <ILogger <IFreeSql> >(); var current = f.GetRequiredService <IOptions <FreeSqlCollectionConfig> >().Value.FreeSqlCollections.FirstOrDefault(x => x.Key == typeof(T).Name); var builder = new FreeSqlBuilder() .UseConnectionString(current.DataType, current.MasterConnetion) .UseAutoSyncStructure(current.IsSyncStructure) .UseMonitorCommand(executing => { executing.CommandTimeout = current.CommandTimeout; if (current.DebugShowSql) { //Console.ForegroundColor = newFontColor; //Console.WriteLine("\n=================================================================================\n"); //Console.WriteLine(executed.CommandText + "\n"); string parametersValue = ""; if (current.DebugShowSqlPparameters) { for (int i = 0; i < executing.Parameters.Count; i++) { parametersValue += $"{executing.Parameters[i].ParameterName}:{executing.Parameters[i].Value}" + ";\n"; } } if (!string.IsNullOrWhiteSpace(parametersValue)) { //Console.WriteLine(parametersValue); log.LogDebug ( "\n=================================================================================\n\n" + executing.CommandText + "\n\n" + "\n" + parametersValue + "\n=================================================================================\n\n" ); } else { log.LogDebug ( "\n=================================================================================\n\n" + executing.CommandText + "\n\n=================================================================================\n" ); } //Console.WriteLine("=================================================================================\n"); //Console.ResetColor(); } }); if (current.SlaveConnections.Count > 0)//判断是否存在从库 { builder.UseSlave(current.SlaveConnections.Select(x => x.ConnectionString).ToArray()); } var res = builder.Build <T>(); #region //使用FreeSql AOP做对应的业务拓展,有需要自行实现 //res.GlobalFilter.Apply<IDeleted>(SysConsts.IsDeletedDataFilter, x => !x.IsDeleted); //res.GlobalFilter.Apply<IEnabled>(SysConsts.IsEnabledDataFilter, x => x.Enabled == true); //res.Aop.ConfigEntity += new EventHandler<ConfigEntityEventArgs>((_, e) => //{ // var attrs = e.EntityType.GetCustomAttributes(typeof(IndexAttribute), false); // foreach (var attr in attrs) // { // var temp = attr as IndexAttribute; // e.ModifyIndexResult.Add(new FreeSql.DataAnnotations.IndexAttribute(temp.Name, temp.Fields, temp.IsUnique)); // } //}); #endregion //使用FreeSql AOP做对应的业务拓展,有需要自行实现 return(res); }); service.AddScoped <IUnitOfWork <T>, UnitOfWork <T> >(); }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="dbConfig"></param> /// <returns></returns> public async static Task AddDbAsync(this IServiceCollection services) { var codeSettings = new ConfigHelper().Get <CodeSettings>("codesettings", AppContext.BaseDirectory); var dbConfig = services.BuildServiceProvider().GetRequiredService <IOptions <DbConfig> >().Value; //创建数据库 if (dbConfig.CreateDb && codeSettings.InitDb) { await DbHelper.CreateDatabase(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure && codeSettings.InitDb) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand && codeSettings.InitDb) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure && codeSettings.InitDb) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig); } //同步数据 if (dbConfig.SyncData && codeSettings.InitDb) { await DbHelper.SyncData(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonData(fsql); } #region 监听Curd操作 if (dbConfig.Curd && codeSettings.InitDb) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 /* * //计算服务器时间 * var serverTime = fsql.Select<T>().Limit(1).First(a => DateTime.local); * var timeOffset = DateTime.UtcNow.Subtract(serverTime); * fsql.Aop.AuditValue += (s, e) => * { * if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) * { * switch (e.Property.Name) * { * case "CreatedTime": * e.Value = DateTime.Now.Subtract(timeOffset); * break; * } * } * else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) * { * switch (e.Property.Name) * { * case "ModifiedTime": * e.Value = DateTime.Now.Subtract(timeOffset); * break; * } * } * }; */ #endregion services.AddSingleton(fsql); #endregion codeSettings.InitDb = false; SuperCodeHelper.SaveSettings(codeSettings); }
/// <summary> /// 注册MySql工作单元服务 /// </summary> /// <typeparam name="TUnitOfWOrk">工作单元接口类型</typeparam> /// <typeparam name="TUnitOfWorkImplementation">工作单元实现类型</typeparam> /// <param name="services">服务集合</param> /// <param name="connection">连接字符串</param> /// <param name="setupAction">配置操作</param> /// <param name="freeSqlSetupAction">FreeSql配置操作</param> public static IServiceCollection AddMySqlUnitOfWork <TUnitOfWOrk, TUnitOfWorkImplementation>(this IServiceCollection services , string connection , Action <FreeSqlBuilder> setupAction = null , Action <IFreeSql> freeSqlSetupAction = null) where TUnitOfWOrk : class, IUnitOfWork where TUnitOfWorkImplementation : UnitOfWorkBase, TUnitOfWOrk { var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(DataType.MySql, connection) .UseLazyLoading(false); setupAction?.Invoke(freeSqlBuilder); var freeSql = freeSqlBuilder.Build(); freeSqlSetupAction?.Invoke(freeSql); freeSql.Aop.AuditValue += (s, e) => { // 乐观锁 if (e.AuditValueType == AuditValueType.Insert || e.AuditValueType == AuditValueType.Update) { if (e.Property.Name == AuditedPropertyConst.Version) { if (e.Value is byte[] bytes && bytes.Length == 0) { e.Value = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); } } } // 时间 if (e.AuditValueType == AuditValueType.Insert) { if (e.Property.Name == AuditedPropertyConst.CreationTime || e.Property.Name == AuditedPropertyConst.ModificationTime) { e.Value = DateTime.Now; } } if (e.AuditValueType == AuditValueType.Update) { if (e.Property.Name == AuditedPropertyConst.ModificationTime) { e.Value = DateTime.Now; } } // 用户 if (e.Property.Name == AuditedPropertyConst.Creator || e.Property.Name == AuditedPropertyConst.Modifier || e.Property.Name == AuditedPropertyConst.CreatorId || e.Property.Name == AuditedPropertyConst.ModifierId) { var currentUser = ServiceLocator.Instance?.GetService <ICurrentUser>(); if (currentUser == null || currentUser.UserId.IsEmpty()) { return; } if (e.AuditValueType == AuditValueType.Insert) { if (e.Property.Name == AuditedPropertyConst.Creator || e.Property.Name == AuditedPropertyConst.Modifier) { e.Value = currentUser.GetFullName() ?? currentUser.GetUserName(); } if (e.Property.Name == AuditedPropertyConst.CreatorId || e.Property.Name == AuditedPropertyConst.ModifierId) { e.Value = currentUser.GetUserId(); } } if (e.AuditValueType == AuditValueType.Update) { if (e.Property.Name == AuditedPropertyConst.Modifier) { e.Value = currentUser.GetFullName() ?? currentUser.GetUserName(); } if (e.Property.Name == AuditedPropertyConst.ModifierId) { e.Value = currentUser.GetUserId(); } } } }; var freeSqlWrapper = new FreeSqlWrapper { Orm = freeSql }; freeSql.GlobalFilter.Apply <ISoftDelete>("SoftDelete", x => x.IsDeleted == false); services.AddSingleton(freeSqlWrapper); services.AddScoped <TUnitOfWOrk, TUnitOfWorkImplementation>(); return(services); }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> /// <param name="appConfig"></param> public async static void AddDb(this IServiceCollection services, IHostEnvironment env, AppConfig appConfig) { var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); //创建数据库 if (dbConfig.CreateDb) { await DbHelper.CreateDatabase(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); //fsql.GlobalFilter.Apply<IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); services.AddFreeRepository(filter => filter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false)); services.AddScoped <UnitOfWorkManager>(); services.AddSingleton(fsql); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig); } //同步数据 if (dbConfig.SyncData) { await DbHelper.SyncData(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonData(fsql); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { System.Threading.Tasks.Parallel.For(0, 1, body => { Console.WriteLine($"{e.Sql}\r\n"); }); }; } #endregion #region 审计数据 //计算服务器时间 //var serverTime = fsql.Select<T>().Limit(1).First(a => DateTime.local); //var timeOffset = DateTime.UtcNow.Subtract(serverTime); var user = services.BuildServiceProvider().GetService <IUser>(); fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; //case "CreatedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; //case "ModifiedTime": // e.Value = DateTime.Now.Subtract(timeOffset); // break; } } }; #endregion #endregion Console.WriteLine($"{appConfig.Urls}\r\n"); }
/// <summary> /// 添加数据库配置 /// </summary> /// <param name="services"></param> /// <param name="appConfig"></param> public static void AddFreesql(this IServiceCollection services, AppConfig appConfig, DbConfig dbConfig) { _services = services; //创建数据库 if (dbConfig.CreateDb) { //await DbHelper.CreateDatabase(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IUser, User>(); services.AddFreeRepository(filter => filter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false)); services.AddScoped <UnitOfWorkManager>(); services.AddSingleton(fsql); services.AddSingleton <ISysFileResponsitory, SysFileResponsitory>(); services.AddSingleton <ISysDicResponsitory, SysDicResponsitory>(); #region 初始化数据库 //同步数据 if (dbConfig.SyncData) { //await DbHelper.SyncData(fsql, dbConfig); } #endregion //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { //await DbHelper.GenerateSimpleJsonData(fsql); } List <string> _md5s = new List <string>(); #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } fsql.Aop.CurdAfter += (s, e) => { if (e.CurdType == FreeSql.Aop.CurdType.Insert || e.CurdType == FreeSql.Aop.CurdType.Update) { //文件,更新为已使用 if (_md5s.Any() && e.EntityType != typeof(SysFile)) { var file = services.BuildServiceProvider().GetService <ISysFileResponsitory>(); file.UpdateDiy.Set(p => p.Used, true).Where(p => _md5s.Contains(p.Md5) && p.Uploaded && !p.Used).ExecuteAffrows(); _md5s.Clear(); } } if (e.ElapsedMilliseconds > 3000) { //TODO 慢SQL提醒开发者 Console.WriteLine($"慢Sql:{e.Sql}\r\n"); } }; #endregion #region 审计数据 fsql.Aop.AuditValue += (s, e) => { if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert || e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { //更新文件为已使用 if (e.Property.GetCustomAttributes(typeof(FileAttribute), false).Any()) { if (e.Value != null && !_md5s.Any(p => p == e.Value.ToString())) { _md5s.Add(e.Value.ToString()); } } var user = services.BuildServiceProvider().GetService <IUser>(); if (user == null || !(user.Id > 0)) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.RealName; break; case "CreatedTime": e.Value = DateTime.Now; break; } } switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; case "ModifiedTime": e.Value = DateTime.Now; break; } } }; #endregion #endregion }
public void ConfigureContainer(ContainerBuilder builder) { #region AutoFac IOC容器 try { var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", _env.EnvironmentName); var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(dbConfig.SyncStructure) .UseLazyLoading(false) .UseNoneCommandParameter(true); var fsql = freeSqlBuilder.Build(); builder.RegisterInstance(fsql).SingleInstance(); builder.RegisterType(typeof(UnitOfWorkManager)).InstancePerLifetimeScope(); builder.RegisterType <HttpContextAccessor>().As <IHttpContextAccessor>().SingleInstance(); builder.RegisterType <User>().As <IUser>().SingleInstance(); builder.RegisterType <UserToken>().As <IUserToken>().InstancePerLifetimeScope(); #region 缓存 var cacheConfig = _configHelper.Get <CacheConfig>("cacheconfig", _env.EnvironmentName); if (cacheConfig.Type == CacheType.Redis) { var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString); RedisHelper.Initialization(csredis); builder.RegisterType <RedisCache>().As <ICache>().SingleInstance(); } else { builder.RegisterType <MicrosoftMemoryCache.MemoryCache>().As <MicrosoftMemoryCache.IMemoryCache>().SingleInstance(); builder.RegisterType <MemoryCache>().As <ICache>().SingleInstance(); } #endregion #region SingleInstance //无接口注入单例 var assemblyCore = Assembly.Load("Web.Core"); var assemblyCommon = Assembly.Load("Admin.Core.Common"); builder.RegisterAssemblyTypes(assemblyCore, assemblyCommon) .Where(t => t.GetCustomAttribute <SingleInstanceAttribute>() != null) .SingleInstance(); //有接口注入单例 builder.RegisterAssemblyTypes(assemblyCore, assemblyCommon) .Where(t => t.GetCustomAttribute <SingleInstanceAttribute>() != null) .AsImplementedInterfaces() .SingleInstance(); #endregion #region Aop var interceptorServiceTypes = new List <Type>(); if (_appConfig.Aop.Transaction) { builder.RegisterType <TransactionInterceptor>(); interceptorServiceTypes.Add(typeof(TransactionInterceptor)); } #endregion #region Repository var assemblyRepository = Assembly.Load("Admin.Core.Repository"); builder.RegisterAssemblyTypes(assemblyRepository) .AsImplementedInterfaces() .InstancePerDependency(); #endregion #region Service var assemblyServices = Assembly.Load("Admin.Core.Service"); builder.RegisterAssemblyTypes(assemblyServices) .AsImplementedInterfaces() .InstancePerDependency() .EnableInterfaceInterceptors() .InterceptedBy(interceptorServiceTypes.ToArray()); #endregion } catch (Exception ex) { throw new Exception(ex.Message + "\n" + ex.InnerException); } #endregion }
public static void AddSimpleFreeSql(this IServiceCollection service) { var thisFontColor = (int)Console.ForegroundColor; var newFontColor = (ConsoleColor)((thisFontColor + 1) > 15 ? 0 : (thisFontColor + 1)); if (service == null) { throw new ArgumentNullException(nameof(service)); } var freeSql = service.BuildServiceProvider().GetRequiredService <IOptions <FreeSqlCollectionConfig> >().Value; var config = freeSql.FreeSqlCollections.Where(it => it.Key == "IHRSystem").FirstOrDefault(); if (config == null) { throw new ArgumentNullException(nameof(config)); } //注入FreeSql service.AddScoped(f => { var log = f.GetRequiredService <ILogger <IFreeSql> >(); var freeBuilder = new FreeSqlBuilder() .UseAutoSyncStructure(false) .UseConnectionString(config.DataType, config.MasterConnetion) .UseLazyLoading(true) .UseMonitorCommand(aop => { //Console.ForegroundColor = newFontColor; //Console.WriteLine("=================================================================================\n"); //Console.WriteLine(aop.CommandText + "\n"); string parametersValue = ""; for (int i = 0; i < aop.Parameters.Count; i++) { parametersValue += $"{aop.Parameters[i].ParameterName}:{aop.Parameters[i].Value}" + ";\n"; } if (!string.IsNullOrWhiteSpace(parametersValue)) { //Console.WriteLine(parametersValue); log.LogInformation ( "\n=================================================================================\n\n" + aop.CommandText + "\n\n" + parametersValue + "\n=================================================================================\n\n" ); } log.LogInformation ( "\n=================================================================================\n\n" + aop.CommandText + "\n\n=================================================================================\n" ); //Console.WriteLine("=================================================================================\n"); //Console.ForegroundColor = (ConsoleColor)thisFontColor; }); if (config.SlaveConnections?.Count > 0)//判断是否存在从库 { freeBuilder.UseSlave(config.SlaveConnections.Select(x => x.ConnectionString).ToArray()); } var freesql = freeBuilder.Build(); //我这里禁用了导航属性联级插入的功能 freesql.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = false); return(freesql); }); //注入Uow service.AddScoped(f => f.GetRequiredService <IFreeSql>().CreateUnitOfWork()); }
/// <summary> /// 注入FreeSql /// </summary> /// <param name="services">IServiceCollection</param> public static void AddFreeSql(this IServiceCollection services) { Log.Logger.Information("Initialize FreeSql Start;"); //获取数据库类型及其连接字符串 var dataTypeValue = NpsEnvironment.NPS_DB_DATETYPE; var dataTypeConnectionString = NpsEnvironment.NPS_DB_MASTERCONNECTSTRING; if (Enum.TryParse(dataTypeValue, out DataType dataType)) { if (!Enum.IsDefined(typeof(DataType), dataType)) { Log.Error($"数据库配置DataType:{dataType}无效"); } if (dataTypeConnectionString.IsNullOrWhiteSpace()) { Log.Error($"数据库配置ConnectionStrings:{dataType}连接字符串无效"); } } else { Log.Error($"数据库配置DataType:{dataTypeValue}无效"); } //创建建造器 var builder = new FreeSqlBuilder() .UseConnectionString(dataType, dataTypeConnectionString) .UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower) //设置是否自动同步表结构,开发环境必备 .UseAutoSyncStructure(NpsEnvironment.NPS_DB_SYNCSTRUCTURE.ToBooleanOrDefault(false)) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //监听所有命令 Log.Logger.Debug($"MonitorCommand:{traceLog};"); }); //生成数据库操作对象 IFreeSql freeSql = builder.Build(); //开启联级保存功能(默认为关闭) freeSql.SetDbContextOptions(opts => opts.EnableAddOrUpdateNavigateList = true); //加载过滤器,设置全局软删除为false freeSql.GlobalFilter.Apply <ISoftDelete>("IsDeleted", a => a.IsDeleted == false); //监听CURD操作 freeSql.Aop.CurdAfter += (s, e) => { //Task.Run(() =>//写法一 Parallel.For(0, 1, a =>//写法二 { //添加MiniProfiler监控SQL性能 MiniProfiler.Current.CustomTiming("SQL:", $"【SQL语句】:{e.Sql},耗时:{e.ElapsedMilliseconds}毫秒"); //若实体中不含DisableSqlCurd标记,则将记录写入至数据库 if (e.EntityType.GetCustomAttribute <DisableSqlCurdAttribute>(false) == null) { //获取ISqlCurdService对象,在获取之前需要注入 var sqlCurdService = services.BuildServiceProvider().GetRequiredService <ISqlCurdService>(); sqlCurdService.Create(new SqlCurdAddInput { FullName = e.EntityType.FullName, ExecuteMilliseconds = e.ElapsedMilliseconds, Sql = e.Sql }); } }); }; //获取IdGenerator对象,在获取之前需要注入 var longGenerator = services.BuildServiceProvider().GetRequiredService <ILongIdGenerator>(); var guidGenerator = services.BuildServiceProvider().GetRequiredService <IGuidGenerator>(); //审计Curd freeSql.Aop.AuditValue += (s, e) => { if (e.Column.CsType == typeof(long)) { if (e.Property.GetCustomAttribute <IdGeneratorAttribute>(false) != null) { if (e.Value?.ToString() == "0") {//当主键为long类型且拥有Id自生成标记且值为0时,主键列不能设置自增属性 e.Value = longGenerator?.Create(); } } } else if (e.Column.CsType == typeof(Guid)) { if (e.Property.GetCustomAttribute <IdGeneratorAttribute>(false) != null) { if (e.Value?.ToString() == "00000000-0000-0000-0000-000000000000") {//当主键为Guid类型且拥有Id自生成标记且值全为0时 e.Value = guidGenerator?.Create(); } } } }; //注入IOC框架 services.AddSingleton(freeSql); //注入仓储 services.AddFreeRepository(); //注入工作单元 services.AddScoped <UnitOfWorkManager>(); //注入SQLCurd语句写入服务 services.AddScoped <ISqlCurdService, SqlCurdService>(); //连接数据库 try { using var masterPool = freeSql.Ado.MasterPool.Get(); } catch (Exception ex) { Log.Logger.Error(ex + ex.StackTrace + ex.Message + ex.InnerException); return; } //同步表结构及初始化数据 try { //注意:只有当CURD到此表时,才会自动生成表结构。 //如需系统运行时迁移表结构,请使用SyncStructure方法 //在运行时直接生成表结构 if (NpsEnvironment.NPS_DB_SYNCSTRUCTURE.ToBooleanOrDefault(false)) { freeSql.CodeFirst .ConfigEntity() .SeedData(NpsEnvironment.NPS_DB_SYNCDATA.ToBooleanOrDefault(false)) //初始化部分数据 .SyncStructure(FreeSqlEntitySyncStructure.FindIEntities(new string[] { "Nps.Data" })); } } catch (Exception ex) { Log.Logger.Error(ex + ex.StackTrace + ex.Message + ex.InnerException); return; } Log.Logger.Information("Initialize FreeSql End;"); }
/// <summary> /// 添加租户数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public static void AddTenantDb(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); var user = services.BuildServiceProvider().GetService <IUser>(); int idleTime = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10; IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime)); ib.TryRegister("tenant_" + user.TenantId.ToString(), () => { #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion var fsql = freeSqlBuilder.Build(); fsql.GlobalFilter.Apply <IEntitySoftDelete>("SoftDelete", a => a.IsDeleted == false); //共享数据库 if (appConfig.TenantType == TenantType.Share) { fsql.GlobalFilter.ApplyIf <ITenant>("Tenant", () => user.TenantId > 0, a => a.TenantId == user.TenantId); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion #region 审计数据 fsql.Aop.AuditValue += (s, e) => { if (user == null || user.Id <= 0) { return; } if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert) { switch (e.Property.Name) { case "CreatedUserId": e.Value = user.Id; break; case "CreatedUserName": e.Value = user.Name; break; case "TenantId": e.Value = user.TenantId; break; } } else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update) { switch (e.Property.Name) { case "ModifiedUserId": e.Value = user.Id; break; case "ModifiedUserName": e.Value = user.Name; break; } } }; #endregion #endregion return(fsql); }); services.AddSingleton(ib); }
/// <summary> /// 添加数据库 /// </summary> /// <param name="services"></param> /// <param name="env"></param> public async static Task AddDbAsync(this IServiceCollection services, IHostEnvironment env) { services.AddScoped <MyUnitOfWorkManager>(); var dbConfig = new ConfigHelper().Get <DbConfig>("dbconfig", env.EnvironmentName); //创建数据库 if (dbConfig.CreateDb) { await DbHelper.CreateDatabaseAsync(dbConfig); } #region FreeSql var freeSqlBuilder = new FreeSqlBuilder() .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString) .UseAutoSyncStructure(false) .UseLazyLoading(false) .UseNoneCommandParameter(true); #region 监听所有命令 if (dbConfig.MonitorCommand) { freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) => { //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n"); Console.WriteLine($"{cmd.CommandText}\r\n"); }); } #endregion 监听所有命令 var fsql = freeSqlBuilder.Build(); //配置实体 var appConfig = new ConfigHelper().Get <AppConfig>("appconfig", env.EnvironmentName); DbHelper.ConfigEntity(fsql, appConfig); #region 初始化数据库 //同步结构 if (dbConfig.SyncStructure) { DbHelper.SyncStructure(fsql, dbConfig: dbConfig, appConfig: appConfig); } #region 审计数据 //计算服务器时间 var serverTime = fsql.Select <DualEntity>().Limit(1).First(a => DateTime.UtcNow); var timeOffset = DateTime.UtcNow.Subtract(serverTime); var user = services.BuildServiceProvider().GetService <IUser>(); DbHelper.TimeOffset = timeOffset; fsql.Aop.AuditValue += (s, e) => { DbHelper.AuditValue(e, timeOffset, user); }; #endregion 审计数据 //同步数据 if (dbConfig.SyncData) { await DbHelper.SyncDataAsync(fsql, dbConfig, appConfig); } #endregion 初始化数据库 //生成数据包 if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData) { await DbHelper.GenerateSimpleJsonDataAsync(fsql, appConfig); } #region 监听Curd操作 if (dbConfig.Curd) { fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine($"{e.Sql}\r\n"); }; } #endregion 监听Curd操作 if (appConfig.Tenant) { fsql.GlobalFilter.Apply <ITenant>("Tenant", a => a.TenantId == user.TenantId); } #endregion FreeSql services.AddSingleton(fsql); //导入多数据库 if (null != dbConfig.Dbs) { foreach (var multiDb in dbConfig.Dbs) { switch (multiDb.Name) { case nameof(MySqlDb): var mdb = CreateMultiDbBuilder(multiDb).Build <MySqlDb>(); services.AddSingleton(mdb); break; default: break; } } } }