|
|
|
|
using DS.Module.Core;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using NLog;
|
|
|
|
|
using SqlSugar;
|
|
|
|
|
|
|
|
|
|
namespace DS.Module.SqlSugar;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// SqlSugar 启动服务
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static class SqlsugarInstall
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 数据库连接字符串
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static string DbInfo = AppSetting.Configuration["ConnectionStrings:DbInfo"];
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 数据库类型
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"];
|
|
|
|
|
|
|
|
|
|
static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 将模块服务添加到依赖注入服务容器中
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="services">依赖注入服务容器</param>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public static IServiceCollection AddSqlsugarInstall(this IServiceCollection services)
|
|
|
|
|
{
|
|
|
|
|
if (services == null) throw new ArgumentNullException(nameof(services));
|
|
|
|
|
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
|
|
|
|
|
{
|
|
|
|
|
DbType = DbType.ToEnum<DbType>(),
|
|
|
|
|
ConnectionString = DbInfo,
|
|
|
|
|
IsAutoCloseConnection = true,
|
|
|
|
|
InitKeyType = InitKeyType.Attribute,
|
|
|
|
|
// AopEvents=aop
|
|
|
|
|
},
|
|
|
|
|
db =>
|
|
|
|
|
{
|
|
|
|
|
//单例参数配置,所有上下文生效
|
|
|
|
|
db.Ado.CommandTimeOut = 30;
|
|
|
|
|
db.Aop.OnLogExecuting = (sql, pars) =>
|
|
|
|
|
{
|
|
|
|
|
Logger.Log(LogLevel.Trace, DateTime.Now.ToString() + "\r\n" + sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
|
|
|
|
|
Logger.Trace(DateTime.Now.ToString() + "\r\n" + sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
|
|
|
|
|
};
|
|
|
|
|
db.Aop.OnError = (exp) => //执行SQL 错误事件
|
|
|
|
|
{
|
|
|
|
|
Logger.Trace(DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres);
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
services.AddSingleton<ISqlSugarClient>(sqlSugar); //这边是SqlSugarScope用AddSingleton
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return services;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|