feat: 优化db连接字符串获取

This commit is contained in:
chenchun
2024-09-25 12:09:34 +08:00
parent bb0e48cd41
commit f499d2d8a9
3 changed files with 32 additions and 42 deletions

View File

@@ -1,13 +1,10 @@
using System; using System.Collections;
using System.Collections;
using System.Reflection; using System.Reflection;
using System.Security.Policy;
using System.Text; using System.Text;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SqlSugar; using SqlSugar;
using Volo.Abp;
using Volo.Abp.Auditing; using Volo.Abp.Auditing;
using Volo.Abp.Data; using Volo.Abp.Data;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
@@ -17,6 +14,7 @@ using Volo.Abp.Guids;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
using Volo.Abp.Users; using Volo.Abp.Users;
using Yi.Framework.SqlSugarCore.Abstractions; using Yi.Framework.SqlSugarCore.Abstractions;
using Check = Volo.Abp.Check;
namespace Yi.Framework.SqlSugarCore namespace Yi.Framework.SqlSugarCore
{ {
@@ -26,24 +24,22 @@ namespace Yi.Framework.SqlSugarCore
/// SqlSugar 客户端 /// SqlSugar 客户端
/// </summary> /// </summary>
public ISqlSugarClient SqlSugarClient { get; private set; } public ISqlSugarClient SqlSugarClient { get; private set; }
public ICurrentUser CurrentUser => LazyServiceProvider.GetRequiredService<ICurrentUser>();
protected ICurrentUser CurrentUser => LazyServiceProvider.GetRequiredService<ICurrentUser>();
private IAbpLazyServiceProvider LazyServiceProvider { get; } private IAbpLazyServiceProvider LazyServiceProvider { get; }
private IGuidGenerator GuidGenerator => LazyServiceProvider.LazyGetRequiredService<IGuidGenerator>(); private IGuidGenerator GuidGenerator => LazyServiceProvider.LazyGetRequiredService<IGuidGenerator>();
protected ILoggerFactory Logger => LazyServiceProvider.LazyGetRequiredService<ILoggerFactory>(); private ILoggerFactory Logger => LazyServiceProvider.LazyGetRequiredService<ILoggerFactory>();
private ICurrentTenant CurrentTenant => LazyServiceProvider.LazyGetRequiredService<ICurrentTenant>(); private ICurrentTenant CurrentTenant => LazyServiceProvider.LazyGetRequiredService<ICurrentTenant>();
public IDataFilter DataFilter => LazyServiceProvider.LazyGetRequiredService<IDataFilter>(); protected IDataFilter DataFilter => LazyServiceProvider.LazyGetRequiredService<IDataFilter>();
protected virtual bool IsMultiTenantFilterEnabled => DataFilter?.IsEnabled<IMultiTenant>() ?? false; protected virtual bool IsMultiTenantFilterEnabled => DataFilter?.IsEnabled<IMultiTenant>() ?? false;
protected virtual bool IsSoftDeleteFilterEnabled => DataFilter?.IsEnabled<ISoftDelete>() ?? false; protected virtual bool IsSoftDeleteFilterEnabled => DataFilter?.IsEnabled<ISoftDelete>() ?? false;
public IEntityChangeEventHelper EntityChangeEventHelper => LazyServiceProvider.LazyGetService<IEntityChangeEventHelper>(NullEntityChangeEventHelper.Instance); private IEntityChangeEventHelper EntityChangeEventHelper => LazyServiceProvider.LazyGetService<IEntityChangeEventHelper>(NullEntityChangeEventHelper.Instance);
public DbConnOptions Options => LazyServiceProvider.LazyGetRequiredService<IOptions<DbConnOptions>>().Value; public DbConnOptions Options => LazyServiceProvider.LazyGetRequiredService<IOptions<DbConnOptions>>().Value;
public AbpDbConnectionOptions ConnectionOptions => LazyServiceProvider.LazyGetRequiredService<IOptions<AbpDbConnectionOptions>>().Value;
public ISerializeService SerializeService=> LazyServiceProvider.LazyGetRequiredService<ISerializeService>(); private ISerializeService SerializeService=> LazyServiceProvider.LazyGetRequiredService<ISerializeService>();
private ISqlSugarDbConnectionCreator _dbConnectionCreator;
public void SetSqlSugarClient(ISqlSugarClient sqlSugarClient) public void SetSqlSugarClient(ISqlSugarClient sqlSugarClient)
{ {
@@ -53,7 +49,6 @@ namespace Yi.Framework.SqlSugarCore
{ {
LazyServiceProvider = lazyServiceProvider; LazyServiceProvider = lazyServiceProvider;
var connectionCreator = LazyServiceProvider.LazyGetRequiredService<ISqlSugarDbConnectionCreator>(); var connectionCreator = LazyServiceProvider.LazyGetRequiredService<ISqlSugarDbConnectionCreator>();
_dbConnectionCreator = connectionCreator;
connectionCreator.OnSqlSugarClientConfig = OnSqlSugarClientConfig; connectionCreator.OnSqlSugarClientConfig = OnSqlSugarClientConfig;
connectionCreator.EntityService = EntityService; connectionCreator.EntityService = EntityService;
connectionCreator.DataExecuting = DataExecuting; connectionCreator.DataExecuting = DataExecuting;
@@ -65,6 +60,7 @@ namespace Yi.Framework.SqlSugarCore
options.ConnectionString = GetCurrentConnectionString(); options.ConnectionString = GetCurrentConnectionString();
options.DbType = GetCurrentDbType(); options.DbType = GetCurrentDbType();
})); }));
//统一使用aop处理
connectionCreator.SetDbAop(SqlSugarClient); connectionCreator.SetDbAop(SqlSugarClient);
//替换默认序列化器 //替换默认序列化器
SqlSugarClient.CurrentConnectionConfig.ConfigureExternalServices.SerializeService = SerializeService; SqlSugarClient.CurrentConnectionConfig.ConfigureExternalServices.SerializeService = SerializeService;
@@ -76,23 +72,12 @@ namespace Yi.Framework.SqlSugarCore
/// <returns></returns> /// <returns></returns>
protected virtual string GetCurrentConnectionString() protected virtual string GetCurrentConnectionString()
{ {
var defautlUrl = Options.Url ?? ConnectionOptions.GetConnectionStringOrNull(ConnectionStrings.DefaultConnectionStringName);
//如果未开启多租户返回db url 或者 默认连接字符串
if (!Options.EnabledSaasMultiTenancy)
{
return defautlUrl;
}
//开启了多租户
var connectionStringResolver = LazyServiceProvider.LazyGetRequiredService<IConnectionStringResolver>(); var connectionStringResolver = LazyServiceProvider.LazyGetRequiredService<IConnectionStringResolver>();
var connectionString = connectionStringResolver.ResolveAsync().GetAwaiter().GetResult(); var connectionString = connectionStringResolver.ResolveAsync().ConfigureAwait(false).GetAwaiter().GetResult();
//没有检测到使用多租户功能,默认使用默认库即可
if (string.IsNullOrWhiteSpace(connectionString)) if (string.IsNullOrWhiteSpace(connectionString))
{ {
Volo.Abp.Check.NotNull(Options.Url, "租户默认库Defalut未找到"); Check.NotNull(Options.Url, "dbUrl未配置");
connectionString = defautlUrl;
} }
return connectionString!; return connectionString!;
} }
@@ -107,7 +92,7 @@ namespace Yi.Framework.SqlSugarCore
return dbTypeFromTenantName.Value; return dbTypeFromTenantName.Value;
} }
} }
Volo.Abp.Check.NotNull(Options.DbType, "默认DbType未配置"); Check.NotNull(Options.DbType, "默认DbType未配置");
return Options.DbType!.Value; return Options.DbType!.Value;
} }
@@ -210,23 +195,22 @@ namespace Yi.Framework.SqlSugarCore
if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreationTime))) if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreationTime)))
{ {
//为空或者为默认最小值 //为空或者为默认最小值
if (oldValue is null || DateTime.MinValue.Equals(oldValue)) if (DateTime.MinValue.Equals(oldValue))
{ {
entityInfo.SetValue(DateTime.Now); entityInfo.SetValue(DateTime.Now);
} }
} }
if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreatorId))) if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreatorId)))
{ {
if (CurrentUser.Id != null) if (CurrentUser.Id is not null)
{ {
entityInfo.SetValue(CurrentUser.Id); entityInfo.SetValue(CurrentUser.Id);
} }
} }
//插入时需要租户id,先预留
if (entityInfo.PropertyName.Equals(nameof(IMultiTenant.TenantId))) if (entityInfo.PropertyName.Equals(nameof(IMultiTenant.TenantId)))
{ {
if (CurrentTenant is not null) if (CurrentTenant.Id is not null)
{ {
entityInfo.SetValue(CurrentTenant.Id); entityInfo.SetValue(CurrentTenant.Id);
} }

View File

@@ -48,7 +48,7 @@ namespace Yi.Framework.SqlSugarCore.Uow
//获取当前连接字符串,未多租户时,默认为空 //获取当前连接字符串,未多租户时,默认为空
var connectionString = await ResolveConnectionStringAsync(connectionStringName); var connectionString = await ResolveConnectionStringAsync(connectionStringName);
var dbContextKey = $"{this.GetType().FullName}_{connectionString}"; var dbContextKey = $"{this.GetType().Name}_{connectionString}";
var unitOfWork = UnitOfWorkManager.Current; var unitOfWork = UnitOfWorkManager.Current;

View File

@@ -25,7 +25,8 @@ namespace Yi.Framework.SqlSugarCore
{ {
var service = context.Services; var service = context.Services;
var configuration = service.GetConfiguration(); var configuration = service.GetConfiguration();
Configure<DbConnOptions>(configuration.GetSection("DbConnOptions")); var section = configuration.GetSection("DbConnOptions");
Configure<DbConnOptions>(section);
service.TryAddScoped<ISqlSugarDbContext, SqlSugarDbContext>(); service.TryAddScoped<ISqlSugarDbContext, SqlSugarDbContext>();
@@ -40,7 +41,12 @@ namespace Yi.Framework.SqlSugarCore
service.AddTransient(typeof(ISugarDbContextProvider<>), typeof(UnitOfWorkSqlsugarDbContextProvider<>)); service.AddTransient(typeof(ISugarDbContextProvider<>), typeof(UnitOfWorkSqlsugarDbContextProvider<>));
//替换Sqlsugar默认序列化器用来解决.Select()不支持嵌套对象/匿名对象的非公有访问器 值无法绑定,如Id属性 //替换Sqlsugar默认序列化器用来解决.Select()不支持嵌套对象/匿名对象的非公有访问器 值无法绑定,如Id属性
context.Services.AddSingleton<ISerializeService,SqlSugarNonPublicSerializer> (); context.Services.AddSingleton<ISerializeService, SqlSugarNonPublicSerializer>();
var dbConfig = section.Get<DbConnOptions>();
//将默认db传递给abp连接字符串模块
Configure<AbpDbConnectionOptions>(x => { x.ConnectionStrings.Default = dbConfig.Url; });
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -51,7 +57,7 @@ namespace Yi.Framework.SqlSugarCore
var service = context.ServiceProvider; var service = context.ServiceProvider;
var options = service.GetRequiredService<IOptions<DbConnOptions>>().Value; var options = service.GetRequiredService<IOptions<DbConnOptions>>().Value;
var _logger= service.GetRequiredService<ILogger<YiFrameworkSqlSugarCoreModule>>(); var logger = service.GetRequiredService<ILogger<YiFrameworkSqlSugarCoreModule>>();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@@ -65,13 +71,14 @@ namespace Yi.Framework.SqlSugarCore
sb.AppendLine("==============================="); sb.AppendLine("===============================");
_logger.LogInformation(sb.ToString()); logger.LogInformation(sb.ToString());
//Todo准备支持多租户种子数据及CodeFirst //Todo准备支持多租户种子数据及CodeFirst
if (options.EnabledCodeFirst) if (options.EnabledCodeFirst)
{ {
CodeFirst(service); CodeFirst(service);
} }
if (options.EnabledDbSeed) if (options.EnabledDbSeed)
{ {
await DataSeedAsync(service); await DataSeedAsync(service);
@@ -80,7 +87,6 @@ namespace Yi.Framework.SqlSugarCore
private void CodeFirst(IServiceProvider service) private void CodeFirst(IServiceProvider service)
{ {
var moduleContainer = service.GetRequiredService<IModuleContainer>(); var moduleContainer = service.GetRequiredService<IModuleContainer>();
var db = service.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient; var db = service.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient;
@@ -95,11 +101,11 @@ namespace Yi.Framework.SqlSugarCore
.Where(x => x.GetCustomAttribute<SugarTable>() != null) .Where(x => x.GetCustomAttribute<SugarTable>() != null)
.Where(x => x.GetCustomAttribute<SplitTableAttribute>() is null)); .Where(x => x.GetCustomAttribute<SplitTableAttribute>() is null));
} }
if (types.Count > 0) if (types.Count > 0)
{ {
db.CopyNew().CodeFirst.InitTables(types.ToArray()); db.CopyNew().CodeFirst.InitTables(types.ToArray());
} }
} }
private async Task DataSeedAsync(IServiceProvider service) private async Task DataSeedAsync(IServiceProvider service)