区分: - GetSqlSugarScope(): 返回 SqlSugarScope,用于 DI 注入(Singleton) - GetSqlSugarClient(): 返回 SqlSugarClient,用于后台任务(每次创建新实例) 原因: - SqlSugarScope 使用 AsyncLocal 隔离上下文 - Task.Run 后台线程中 AsyncLocal 可能无法正确传递 - 后台任务使用 SqlSugarClient 更安全,每个实例独立连接 使用: - DI 注入:GetSqlSugarScope() - Repository 后台写入:GetSqlSugarClient() - 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)
|
|
{
|
|
// SqlSugarScope 是线程安全的,内部使用 AsyncLocal 隔离上下文
|
|
// 使用 Singleton 注册,整个应用共享一个实例
|
|
services.AddSingleton<ISqlSugarClient>(s =>
|
|
{
|
|
return SqlSugarConfig.GetSqlSugarScope();
|
|
});
|
|
|
|
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();
|
|
}
|
|
}
|