Files
2026-04-30 11:34:41 +08:00

109 lines
3.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Models.Const;
using SamplePre.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.DAL.DBContext
{
public class DBFactory
{
#region
private static readonly Lazy<SqlSugarClient> _lazySqlSugarClient = new Lazy<SqlSugarClient>(() =>
{
return CreateSqlSugarClient();
});
/// <summary>
/// 获取默认数据库的SqlSugarClient单例实例
/// </summary>
public static SqlSugarClient Instance => _lazySqlSugarClient.Value;
#endregion
#region App.config读取的配置项
private static readonly string _connStr; // 数据库连接字符串
private static readonly bool _isAutoCloseConn; // 是否自动关闭连接
/// <summary>
/// 静态构造函数读取App.config配置初始化全局参数
/// </summary>
static DBFactory()
{
try
{
// 1. 读取数据库连接字符串MySQL
_connStr = SystemConst.SysConfigInfo.DbConfig.MySql.ConnStr;//"Data Source=localhost;Database=fanghuayuan;AllowLoadLocalInfile=true;User ID=root;Password=123;allowPublicKeyRetrieval=true;pooling=true;port=3306;";
// 2. 读取SqlSugar全局配置AppSettings节点
_isAutoCloseConn = true;//Convert.ToBoolean(ConfigurationManager.AppSettings["SqlSugar_IsAutoCloseConnection"]);
}
catch (Exception ex)
{
throw new Exception("SqlSugar工厂类配置读取失败" + ex.Message);
}
}
#endregion
#region SqlSugarClient并配置全局参数
/// <summary>
/// 封装SqlSugarClient的创建、数据库配置、全局AOP
/// </summary>
/// <returns>配置完成的SqlSugarClient实例</returns>
private static SqlSugarClient CreateSqlSugarClient()
{
// 1. 数据库连接核心配置按需修改DbType对应连接字符串
var connectionConfig = new ConnectionConfig
{
ConnectionString = _connStr, // 连接字符串
DbType = SqlSugar.DbType.MySql, // 数据库类型:
IsAutoCloseConnection = _isAutoCloseConn, // 自动关闭连接(必开,避免连接泄漏)
InitKeyType = InitKeyType.Attribute, // 从实体类特性读取主键/自增配置(核心)
};
// 2. 创建SqlSugarClient实例
var db = new SqlSugarClient(connectionConfig);
db.Aop.OnError = (ex) =>
{
string errorLog = $@"【SQL执行异常】{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}
【异常信息】{ex.Message}
【SQL语句】{ex.Sql}";
// 异常日志写入本地文件
LoggerHelper.Logger.Error(errorLog);
};
return db;
}
#endregion
#region 退
/// <summary>
/// 手动释放SqlSugarClient资源仅特殊场景使用
/// </summary>
public static void DisposeInstance()
{
if (_lazySqlSugarClient.IsValueCreated)
{
Instance.Dispose();
}
}
#endregion
}
}