AssetManager.API/AssetManager.Data/DatabaseExtensions.cs
OpenClaw Agent 8d7e62f8af fix: SqlSugar 注册改为 Scoped 避免并发冲突
问题:
- ISqlSugarClient 注册为 Singleton
- 多个请求共享同一个 SqlSugarScope 实例
- Task.WhenAll 并发查询时连接状态冲突

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

配合内存缓存层,双重保障:
1. 内存缓存:减少数据库查询次数
2. Scoped:隔离请求间的连接对象
2026-03-24 09:59:30 +00:00

34 lines
1.0 KiB
C#
Executable File

using AssetManager.Data.Repositories;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace AssetManager.Data;
public static class DatabaseExtensions
{
public static IServiceCollection AddDatabase(this IServiceCollection services)
{
// 使用 Scoped 注册,每个 HTTP 请求一个实例,避免并发冲突
// SqlSugarScope 内部会自动管理连接池
services.AddScoped<ISqlSugarClient>(s =>
{
return SqlSugarConfig.GetSqlSugarClient();
});
services.AddScoped<DatabaseService>();
// Repository 层
services.AddScoped<IPortfolioRepository, PortfolioRepository>();
services.AddScoped<IMarketDataRepository, MarketDataRepository>();
return services;
}
public static void InitializeDatabase(this IServiceProvider serviceProvider)
{
using var scope = serviceProvider.CreateScope();
var dbService = scope.ServiceProvider.GetRequiredService<DatabaseService>();
dbService.InitializeDatabase();
}
}