官方建议: - SqlSugarClient 超高性能模式 - 每次 new 创建实例 - IsAutoCloseConnection=true 自动关闭连接 - 适合 DI Scoped 注入、后台任务、Task.Run 场景 修改: 1. DI 注入改为 Scoped(每次 HTTP 请求一个实例) 2. 移除 SqlSugarScope,统一使用 SqlSugarClient 3. 后台任务创建新实例(已实现) 4. MySQL 连接池复用底层 TCP 连接 优点: - 性能更好 - 代码更简单 - 符合官方最佳实践
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)
|
|
{
|
|
// SqlSugarClient 超高性能模式:每次请求创建新实例
|
|
// Scoped 确保:同一 HTTP 请求内复用,不同请求隔离
|
|
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();
|
|
}
|
|
}
|