using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.Core.Modules;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SqlSugar;
namespace DS.Module.SqlSugar;
///
/// SqlSugar模块
///
public class SqlSugarModule : DSAppModule
{
///
/// 数据库连接字符串
///
private static string DbInfo = AppSetting.Configuration["ConnectionStrings:DbInfo"];
///
/// 数据库类型
///
private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"];
private ILogger _logger;
public override void ConfigureServices(ConfigureServicesContext context)
{
_logger = context.Services.GetService>();
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
DbType = DbType.ToEnum(),
ConnectionString = DbInfo,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
// AopEvents=aop
},
db =>
{
//单例参数配置,所有上下文生效
db.Ado.CommandTimeOut = 30;
db.Aop.OnLogExecuting = (sql, pars) =>
{
_logger.Log(LogLevel.Information, 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.Log(LogLevel.Error, DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres);
};
});
context.Services.AddSingleton(sqlSugar); //这边是SqlSugarScope用AddSingleton
}
}