67 lines
2.8 KiB
C#
67 lines
2.8 KiB
C#
using Mapster;
|
||
using MapsterMapper;
|
||
using Newtonsoft.Json.Converters;
|
||
using Newtonsoft.Json.Serialization;
|
||
using Newtonsoft.Json;
|
||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||
using Microsoft.IdentityModel.Tokens;
|
||
using System.Text;
|
||
using System.Reflection.Metadata;
|
||
using SqlSugar;
|
||
using System.Text.RegularExpressions;
|
||
|
||
namespace WGShare.API.ServiceConfigs
|
||
{
|
||
public static class SqlsugarServiceExtensions
|
||
{
|
||
/// <summary>
|
||
/// 添加SqlSugar
|
||
/// </summary>
|
||
/// <param name="services">服务集合</param>
|
||
/// <returns></returns>
|
||
public static IServiceCollection AddSqlsugar(this IServiceCollection services, string env, params ConnectionConfig[] connectionConfigs)
|
||
{
|
||
SqlSugarScope sqlSugar = new SqlSugarScope(connectionConfigs.ToList(),
|
||
db =>
|
||
{
|
||
if (env == Environments.Development)
|
||
{
|
||
// 正则表达式匹配Ip
|
||
var ipMatch = Regex.Match(db.CurrentConnectionConfig.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 = db.CurrentConnectionConfig.ConnectionString.Split(';');
|
||
string dbNamne = string.Empty;
|
||
foreach (var item in connections)
|
||
{
|
||
if (item.Contains("Database"))
|
||
{
|
||
dbNamne = item.Split('=')[1];
|
||
}
|
||
}
|
||
|
||
//SQL执行前
|
||
db.Aop.OnLogExecuting = (sql, pars) =>
|
||
{
|
||
// 打印 Sql 语句
|
||
Console.WriteLine($@"{new string('=', 10)}BEGIN{new string('=', 5)} DB-IP:{ipMatch.Value} {new string('=', 5)} DB-Name:{dbNamne} {new string('=', 15)}");
|
||
Console.WriteLine($"执行Sql:{Environment.NewLine}{sql}");
|
||
Console.WriteLine($"参数:{db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))}");
|
||
};
|
||
|
||
//SQL执行完成
|
||
db.Aop.OnLogExecuted = (sql, pars) =>
|
||
{
|
||
//执行完了可以输出SQL执行时间
|
||
Console.WriteLine("Sql用时:" + db.Ado.SqlExecutionTime.ToString());
|
||
Console.WriteLine($@"{new string('=', 10)}END{new string('=', 7)} DB-IP:{ipMatch.Value} {new string('=', 5)} DB-Name:{dbNamne} {new string('=', 15)}");
|
||
};
|
||
}
|
||
});
|
||
|
||
services.AddSingleton<ISqlSugarClient>(sqlSugar);
|
||
|
||
return services;
|
||
}
|
||
}
|
||
}
|