问题:Cannot Open when State is Connecting 分析: - SqlSugarScope 是线程安全的,使用 AsyncLocal 隔离上下文 - Singleton 注册符合官方建议 - 问题可能出在 MySQL 连接池配置 修复: 添加连接池参数: - Pooling=true(开启连接池) - MaximumPoolSize=100(最大连接数) - MinimumPoolSize=5(最小连接数) - ConnectionTimeout=30(连接超时) - ConnectionIdleTimeout=180(空闲连接超时,避免使用陈旧连接) 配合内存缓存层,减少数据库查询次数
34 lines
1.1 KiB
C#
Executable File
34 lines
1.1 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)
|
|
{
|
|
// SqlSugarScope 是线程安全的,内部使用 AsyncLocal 隔离上下文
|
|
// 使用 Singleton 注册,整个应用共享一个实例
|
|
services.AddSingleton<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();
|
|
}
|
|
}
|