using System.Collections.Concurrent;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SqlSugar;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Threading;
using Volo.Abp.Users;
using Yi.Framework.SqlSugarCore.Abstractions;
using Check = Volo.Abp.Check;
namespace Yi.Framework.SqlSugarCore
{
///
/// SqlSugar数据库上下文工厂类
/// 负责创建和配置SqlSugar客户端实例
///
public class SqlSugarDbContextFactory : ISqlSugarDbContext
{
#region Properties
///
/// SqlSugar客户端实例
///
public ISqlSugarClient SqlSugarClient { get; private set; }
///
/// 延迟服务提供者
///
private IAbpLazyServiceProvider LazyServiceProvider { get; }
///
/// 租户配置包装器
///
private TenantConfigurationWrapper TenantConfigurationWrapper =>
LazyServiceProvider.LazyGetRequiredService();
///
/// 当前租户信息
///
private ICurrentTenant CurrentTenant =>
LazyServiceProvider.LazyGetRequiredService();
///
/// 数据库连接配置选项
///
private DbConnOptions DbConnectionOptions =>
LazyServiceProvider.LazyGetRequiredService>().Value;
///
/// 序列化服务
///
private ISerializeService SerializeService =>
LazyServiceProvider.LazyGetRequiredService();
///
/// SqlSugar上下文依赖项集合
///
private IEnumerable SqlSugarDbContextDependencies =>
LazyServiceProvider.LazyGetRequiredService>();
///
/// 连接配置缓存字典
///
private static readonly ConcurrentDictionary ConnectionConfigCache = new();
#endregion
///
/// 构造函数
///
/// 延迟服务提供者
public SqlSugarDbContextFactory(IAbpLazyServiceProvider lazyServiceProvider)
{
LazyServiceProvider = lazyServiceProvider;
// 异步获取租户配置
var tenantConfiguration = AsyncHelper.RunSync(async () => await TenantConfigurationWrapper.GetAsync());
// 构建数据库连接配置
var connectionConfig = BuildConnectionConfig(options =>
{
options.ConnectionString = tenantConfiguration.GetCurrentConnectionString();
options.DbType = GetCurrentDbType(tenantConfiguration.GetCurrentConnectionName());
});
// 创建SqlSugar客户端实例
SqlSugarClient = new SqlSugarClient(connectionConfig);
// 配置数据库AOP
ConfigureDbAop(SqlSugarClient);
}
///
/// 配置数据库AOP操作
///
/// SqlSugar客户端实例
protected virtual void ConfigureDbAop(ISqlSugarClient sqlSugarClient)
{
// 配置序列化服务
sqlSugarClient.CurrentConnectionConfig.ConfigureExternalServices.SerializeService = SerializeService;
// 初始化AOP事件处理器
Action onLogExecuting = null;
Action onLogExecuted = null;
Action