109 lines
3.6 KiB
C#
109 lines
3.6 KiB
C#
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
|
||
|
||
|
||
|
||
}
|
||
}
|