🍒 fix(LazyServer): 修复懒加载服务异常的问题

This commit is contained in:
喵你个汪呀 2025-09-02 20:59:29 +08:00
parent b5b03b90ca
commit 002bc90c81
13 changed files with 40 additions and 22 deletions

View File

@ -188,7 +188,7 @@ public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable
/// <returns></returns> /// <returns></returns>
private LoggingUserInfo GetUserInfo(LoggingMonitorDto loggingMonitor) private LoggingUserInfo GetUserInfo(LoggingMonitorDto loggingMonitor)
{ {
var userManger = LazyHelper.GetService<UserManager>(); var userManger = LazyHelper.GetService<UserManager>().Value;
LoggingUserInfo result = new(); LoggingUserInfo result = new();
if (loggingMonitor.AuthorizationClaims != null) if (loggingMonitor.AuthorizationClaims != null)
{ {

View File

@ -42,7 +42,7 @@ public class ElasticSearchLoggingWriter : IDatabaseLoggingWriter, IDisposable
return; return;
// 获取当前操作者 // 获取当前操作者
var userManager = LazyHelper.GetService<UserManager>(); var userManager = LazyHelper.GetService<UserManager>().Value;
string account = "", realName = "", userId = "", tenantId = ""; string account = "", realName = "", userId = "", tenantId = "";
if (loggingMonitor.authorizationClaims != null) if (loggingMonitor.authorizationClaims != null)
{ {

View File

@ -38,7 +38,7 @@ public class HttpLoggingHandler : DelegatingHandler, ITransient
if (!enabledLog || attr?.IgnoreLog == true) return await base.SendAsync(request, cancellationToken); if (!enabledLog || attr?.IgnoreLog == true) return await base.SendAsync(request, cancellationToken);
var stopWatch = Stopwatch.StartNew(); var stopWatch = Stopwatch.StartNew();
var userManger = LazyHelper.GetService<UserManager>(); var userManger = LazyHelper.GetService<UserManager>().Value;
var urlList = request.RequestUri?.LocalPath.Split("/") ?? []; var urlList = request.RequestUri?.LocalPath.Split("/") ?? [];
var sysLogHttp = new SysLogHttp var sysLogHttp = new SysLogHttp
{ {

View File

@ -288,9 +288,11 @@ public class SysAuthService : IDynamicApiController, ITransient
user.SysPos ??= await db.Queryable<SysPos>().FirstAsync(u => u.Id == user.PosId); user.SysPos ??= await db.Queryable<SysPos>().FirstAsync(u => u.Id == user.PosId);
user.SysOrg ??= await db.Queryable<SysOrg>().FirstAsync(u => u.Id == user.OrgId); user.SysOrg ??= await db.Queryable<SysOrg>().FirstAsync(u => u.Id == user.OrgId);
var permissions = await LazyHelper.GetService<SysRoleService>().GetUserApiList(user.Id); var sysRoleService = LazyHelper.GetService<SysRoleService>().Value;
var unauthorizedPermissions = await LazyHelper.GetService<SysRoleService>().GetUnAuthApiList(user.Id); var sysOrgService = LazyHelper.GetService<SysOrgService>().Value;
var orgIds = await LazyHelper.GetService<SysOrgService>().GetUserOrgIdList(user.Id, user.OrgId); var permissions = await sysRoleService.GetUserApiList(user.Id);
var unauthorizedPermissions = await sysRoleService.GetUnAuthApiList(user.Id);
var orgIds = await sysOrgService.GetUserOrgIdList(user.Id, user.OrgId);
var roleIds = await db.Queryable<SysUserRole>().Where(u => u.UserId == user.Id).Select(u => u.RoleId).ToListAsync(); var roleIds = await db.Queryable<SysUserRole>().Where(u => u.UserId == user.Id).Select(u => u.RoleId).ToListAsync();
var postIds = await db.Queryable<SysUserExtOrg>().Where(u => u.UserId == user.Id).Select(u => u.PosId).ToListAsync() ?? []; var postIds = await db.Queryable<SysUserExtOrg>().Where(u => u.UserId == user.Id).Select(u => u.PosId).ToListAsync() ?? [];
var maxDataScope = await db.Queryable<SysRole>().Where(u => roleIds.Contains(u.Id)).MinAsync(u => u.DataScope); var maxDataScope = await db.Queryable<SysRole>().Where(u => roleIds.Contains(u.Id)).MinAsync(u => u.DataScope);
@ -321,7 +323,7 @@ public class SysAuthService : IDynamicApiController, ITransient
RoleIds = roleIds, RoleIds = roleIds,
Permissions = permissions, Permissions = permissions,
UnauthorizedPermissions = unauthorizedPermissions, UnauthorizedPermissions = unauthorizedPermissions,
AppPermissions = loginMode == LoginModeEnum.APP ? LazyHelper.GetService<SysCommonService>().GetAppApiList() : null, AppPermissions = loginMode == LoginModeEnum.APP ? LazyHelper.GetService<SysCommonService>().Value.GetAppApiList() : null,
MaxDataScope = user.AccountType == AccountTypeEnum.SuperAdmin ? DataScopeEnum.All : maxDataScope, MaxDataScope = user.AccountType == AccountTypeEnum.SuperAdmin ? DataScopeEnum.All : maxDataScope,
ExtProps = App.GetServices<IUserSessionExtProps>().SelectMany(u => u.GetInitExtProps(user)).ToDictionary(u => u.Key, u => u.Value) ExtProps = App.GetServices<IUserSessionExtProps>().SelectMany(u => u.GetInitExtProps(user)).ToDictionary(u => u.Key, u => u.Value)
}); });

View File

@ -431,7 +431,8 @@ public class SysCacheService : IDynamicApiController, ISingleton
public void Clear() public void Clear()
{ {
// 超管用户操作,清空所有缓存 // 超管用户操作,清空所有缓存
if (LazyHelper.GetService<UserManager>().SuperAdmin) var userManager = App.GetService<UserManager>();
if (userManager.SuperAdmin)
{ {
_cacheProvider.Cache.Clear(); _cacheProvider.Cache.Clear();
Cache.Default.Clear(); Cache.Default.Clear();

View File

@ -211,7 +211,7 @@ public class UserManager(
if (long.TryParse(userId.ToString(), out long tempId)) userId = tempId; if (long.TryParse(userId.ToString(), out long tempId)) userId = tempId;
else return null; else return null;
} }
LazyHelper.GetService<SysAuthService>().RefreshSession(userId).GetAwaiter().GetResult(); LazyHelper.GetService<SysAuthService>().Value.RefreshSession(userId).GetAwaiter().GetResult();
} }
return sysCacheService.Get<UserSessionDao>(CacheConst.KeyUserSession + userId); return sysCacheService.Get<UserSessionDao>(CacheConst.KeyUserSession + userId);
} }

View File

@ -584,7 +584,7 @@ public static class SqlSugarExtension
// 使用线程安全的延迟初始化服务实例获取文本缩写 // 使用线程安全的延迟初始化服务实例获取文本缩写
var abbrValue = LazyHelper.GetService<SysCommonService>() var abbrValue = LazyHelper.GetService<SysCommonService>()
.GetNameAbbr(new() { Text = value, All = attribute.SaveFullAbbr }) .Value.GetNameAbbr(new() { Text = value, All = attribute.SaveFullAbbr })
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
entityInfo.SetValue(abbrValue); entityInfo.SetValue(abbrValue);
@ -634,7 +634,7 @@ public static class SqlSugarExtension
// 使用线程安全的延迟初始化服务实例获取流水号 // 使用线程安全的延迟初始化服务实例获取流水号
var serial = LazyHelper.GetService<SysSerialService>() var serial = LazyHelper.GetService<SysSerialService>()
.NextSeqNo(attribute.Type, attribute.IsGlobal) .Value.NextSeqNo(attribute.Type, attribute.IsGlobal)
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
entityInfo.SetValue(serial); entityInfo.SetValue(serial);

View File

@ -59,7 +59,8 @@ public static class SqlSugarFilter
if (string.IsNullOrWhiteSpace(userId)) return; if (string.IsNullOrWhiteSpace(userId)) return;
// 获取用户session // 获取用户session
var session = LazyHelper.GetService<UserManager>().GetSessionOrRefresh(userId); var userManager = LazyHelper.GetService<UserManager>().Value;
var session = userManager.GetSessionOrRefresh(userId);
if (session == null) return; if (session == null) return;
// 配置用户机构集合缓存 // 配置用户机构集合缓存
@ -113,7 +114,8 @@ public static class SqlSugarFilter
if (string.IsNullOrWhiteSpace(userId)) return maxDataScope; if (string.IsNullOrWhiteSpace(userId)) return maxDataScope;
// 获取用户session // 获取用户session
var session = LazyHelper.GetService<UserManager>().GetSessionOrRefresh(userId); var userManager = LazyHelper.GetService<UserManager>().Value;
var session = userManager.GetSessionOrRefresh(userId);
if (session == null) return (int)DataScopeEnum.Self; if (session == null) return (int)DataScopeEnum.Self;
// 获取用户最大数据范围---仅本人数据 // 获取用户最大数据范围---仅本人数据

View File

@ -37,7 +37,8 @@ public class SqlSugarRepository<T> : SimpleClient<T>, ISqlSugarRepository<T> whe
return; return;
// 若未贴任何表特性或当前未登录或是默认租户Id则返回默认库连接 // 若未贴任何表特性或当前未登录或是默认租户Id则返回默认库连接
var tenantId = LazyHelper.GetService<UserManager>().TenantId?.ToString(); var userManager = LazyHelper.GetService<UserManager>().Value;
var tenantId = userManager.TenantId?.ToString();
if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return; if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
// 根据租户Id切换库连接, 为空则返回默认库连接 // 根据租户Id切换库连接, 为空则返回默认库连接

View File

@ -215,7 +215,7 @@ public static class SqlSugarSetup
Log.Warning(log); Log.Warning(log);
}; };
var userManager = LazyHelper.GetService<UserManager>(); var userManager = LazyHelper.GetService<UserManager>().Value;
// 数据审计 // 数据审计
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) => dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{ {

View File

@ -6,18 +6,29 @@
namespace Admin.NET.Core; namespace Admin.NET.Core;
/// <summary>
/// 懒加载帮助类
/// </summary>
public class LazyHelper public class LazyHelper
{ {
private static readonly Dictionary<Type, Lazy<object>> _cache = new(); private static readonly ConcurrentDictionary<Type, Lazy<object>> Cache = new();
/// <summary> /// <summary>
/// 获取服务 /// 获取服务
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static T GetService<T>() where T : class public static Lazy<T> GetService<T>() where T : class
{ {
if (_cache.TryGetValue(typeof(T), out var lazy)) return (T)lazy.Value; try
return (T)(_cache[typeof(T)] = new Lazy<object>(() => App.GetService<T>())).Value; {
var lazy = Cache.GetOrAdd(typeof(T), _ => new Lazy<object>(() => App.GetService<T>()));
return (Lazy<T>)(object)lazy;
}
catch (Exception)
{
Cache.Remove(typeof(T), out _);
return null;
}
} }
} }

View File

@ -91,7 +91,8 @@ namespace Admin.NET.Web.Core
} }
// 验证租户有效期 // 验证租户有效期
var tenantId = LazyHelper.GetService<UserManager>().TenantId?.ToString(); var userManager = LazyHelper.GetService<UserManager>().Value;
var tenantId = userManager.TenantId?.ToString();
if (!string.IsNullOrWhiteSpace(tenantId)) if (!string.IsNullOrWhiteSpace(tenantId))
{ {
var tenant = sysCacheService.Get<List<SysTenant>>(CacheConst.KeyTenant)?.FirstOrDefault(u => u.Id == long.Parse(tenantId)); var tenant = sysCacheService.Get<List<SysTenant>>(CacheConst.KeyTenant)?.FirstOrDefault(u => u.Id == long.Parse(tenantId));
@ -117,7 +118,7 @@ namespace Admin.NET.Web.Core
/// <returns></returns> /// <returns></returns>
private static async Task<bool> CheckAuthorizeAsync(DefaultHttpContext httpContext) private static async Task<bool> CheckAuthorizeAsync(DefaultHttpContext httpContext)
{ {
var userManager = LazyHelper.GetService<UserManager>(); var userManager = LazyHelper.GetService<UserManager>().Value;
// 排除超管权限判断 // 排除超管权限判断
if (userManager?.AccountType == AccountTypeEnum.SuperAdmin) return true; if (userManager?.AccountType == AccountTypeEnum.SuperAdmin) return true;

View File

@ -61,7 +61,7 @@ public class SuperApiAop : DefaultSuperApiAop
var paths = api?.Url?.Split('/'); var paths = api?.Url?.Split('/');
var actionName = paths?[^1]; var actionName = paths?[^1];
var userManager = LazyHelper.GetService<UserManager>(); var userManager = LazyHelper.GetService<UserManager>().Value;
var apiInfo = new var apiInfo = new
{ {
requestUrl = api?.Url, requestUrl = api?.Url,