fix: SqlSugar 注册改为 Scoped 避免并发冲突

问题:
- ISqlSugarClient 注册为 Singleton
- 多个请求共享同一个 SqlSugarScope 实例
- Task.WhenAll 并发查询时连接状态冲突

修复:
- Singleton → Scoped
- 每个 HTTP 请求独立的 SqlSugarScope 实例
- 避免跨请求共享连接对象

配合内存缓存层,双重保障:
1. 内存缓存:减少数据库查询次数
2. Scoped:隔离请求间的连接对象
This commit is contained in:
OpenClaw Agent 2026-03-24 09:59:30 +00:00
parent 9014363d6d
commit 8d7e62f8af

View File

@ -8,9 +8,9 @@ public static class DatabaseExtensions
{ {
public static IServiceCollection AddDatabase(this IServiceCollection services) public static IServiceCollection AddDatabase(this IServiceCollection services)
{ {
// 使用 Singleton 注册 SqlSugarScope线程安全内部使用 AsyncLocal // 使用 Scoped 注册,每个 HTTP 请求一个实例,避免并发冲突
// SqlSugarScope 设计上支持并发,会自动管理连接池 // SqlSugarScope 内部会自动管理连接池
services.AddSingleton<ISqlSugarClient>(s => services.AddScoped<ISqlSugarClient>(s =>
{ {
return SqlSugarConfig.GetSqlSugarClient(); return SqlSugarConfig.GetSqlSugarClient();
}); });