using DS.WMS.PrintApi.Utils; using Microsoft.Extensions.DependencyInjection; using NLog; using SqlSugar; using System; using System.Collections.Generic; using DbType = SqlSugar.DbType; namespace DS.WMS.PrintApi.Middleware { /// /// SqlSugar 启动服务 /// public static class SqlSugarSetup { public static readonly Logger Logger = LogManager.GetCurrentClassLogger(); /// /// 默认的Sql Server的链接字符串 /// private static string ProTag = AppSetting.Configuration["ConnectionStrings:Pro"]; private static string DataType = AppSetting.Configuration["ConnectionStrings:DbType"]; /// /// 将模块服务添加到依赖注入服务容器中 /// /// 依赖注入服务容器 /// public static IServiceCollection AddSqlSugarSetup(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); SqlSugarScope sqlSugar = new SqlSugarScope(new List() { new ConnectionConfig() { ConfigId = "1288018625843826688", DbType = DataType.ToEnum(), ConnectionString = ProTag, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true }, //new ConnectionConfig(){ ConfigId="2", DbType=DbType.SqlServer, ConnectionString=DevTag,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true,AopEvents=aop} }); //db.ChangeDatabase(configId); //记录数据库配置 //Console.WriteLine("数据库配置:"+JsonConvert.SerializeObject(db.CurrentConnectionConfig)); //Logger.Log(LogLevel.Trace, JsonConvert.SerializeObject(db.CurrentConnectionConfig)); sqlSugar.Ado.CommandTimeOut = 30; sqlSugar.Aop.OnLogExecuting = (sql, pars) => { Logger.Log(LogLevel.Info, DateTime.Now.ToString() + "\r\n" + UtilMethods.GetSqlString(DataType.ToEnum(), sql, pars)); }; sqlSugar.Aop.OnError = (exp) => //执行SQL 错误事件 { // Console.WriteLine(DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres); Logger.Error(DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres); //Logger.Log(LogLevel.Error, DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres); //exp.sql exp.parameters 可以拿到参数和错误Sql }; services.AddSingleton(sqlSugar); //这边是SqlSugarScope用AddSingleton return services; } } }