using System.ComponentModel.DataAnnotations;
using System.Reflection;
using JNPF;
using JNPF.DatabaseAccessor;
using JNPF.Logging;
using Spire.Xls;
using SqlSugar;
namespace Microsoft.Extensions.DependencyInjection;
///
/// SqlSugar配置拓展.
///
public static class ConfigureSqlSugarExtensions
{
public static IServiceCollection ConfigureSqlSugar(this IServiceCollection services)
{
// 获取选项
ConnectionStringsOptions conn = App.GetConfig("ConnectionStrings", true);
List connectConfigList = new List();
var DBType = (DbType)Enum.Parse(typeof(DbType), conn.DBType);
// 默认数据库
connectConfigList.Add(new ConnectionConfig
{
ConnectionString = string.Format(conn.DefaultConnection, conn.Host, conn.Port, conn.DBName, conn.UserName, conn.Password),
DbType = DBType,
IsAutoCloseConnection = true,
ConfigId = conn.ConfigId,
InitKeyType = InitKeyType.Attribute,
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true // 自动清理缓存
},
});
services.AddSqlSugar(connectConfigList, client =>
{
//connectConfigList.ForEach(config =>
//{
// var db = ((SqlSugarScope)client).GetConnectionScope((string)config.ConfigId);
// // 设置超时时间
// db.Ado.CommandTimeOut = 30;
// db.Aop.OnLogExecuted = (sql, pars) =>
// {
// var oldColor = Console.ForegroundColor;
// Console.ForegroundColor = ConsoleColor.Green;
// var finalSql = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars);
// Console.WriteLine($"【{DateTime.Now.ToString("HH:mm:ss.fff")}——SQL执行完成】{db.Ado.SqlExecutionTime.TotalMilliseconds} ms");
// Console.WriteLine(finalSql);
// Console.ForegroundColor = oldColor;
// if (db.Ado.SqlExecutionTime.TotalMilliseconds > 3000)
// {
// Log.Warning($"慢查询: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms, SQL: " + finalSql);
// }
// Console.WriteLine();
// };
// db.Aop.OnError = (ex) =>
// {
// Log.Error(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, ex.Sql, (SugarParameter[])ex.Parametres));
// };
//});
});
services.AddConfigurableOptions();
services.AddConfigurableOptions();
services.AddUnitOfWork();
return services;
}
}