AssetManager.API/AssetManager.Data/DatabaseExtensions.cs

34 lines
1.1 KiB
C#
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AssetManager.Data.Repositories;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace AssetManager.Data;
public static class DatabaseExtensions
{
public static IServiceCollection AddDatabase(this IServiceCollection services)
{
// 使用 Singleton 注册 SqlSugarScope线程安全内部使用 AsyncLocal
// SqlSugarScope 设计上支持并发,会自动管理连接池
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();
}
}