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(s => { return SqlSugarConfig.GetSqlSugarClient(); }); services.AddScoped(); // Repository 层 services.AddScoped(); services.AddScoped(); return services; } public static void InitializeDatabase(this IServiceProvider serviceProvider) { using var scope = serviceProvider.CreateScope(); var dbService = scope.ServiceProvider.GetRequiredService(); dbService.InitializeDatabase(); } }