using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace FileShare_EFCore.Database { /// /// 数据库服务注册扩展 —— 在 Program.cs 中一行配置数据库。 /// public static class DatabaseExtensions { /// /// 注册数据库上下文及相关服务。 /// /// 继承自 AppDbContext 的业务 DbContext public static IServiceCollection AddAppDatabase( this IServiceCollection services, DatabaseConfiguration config) where TContext : AppDbContext { // 注册配置 services.AddSingleton(config); if (typeof(TContext) == typeof(AppDataContext)) { services.AddProviderAppDataContext(config); services.AddScoped>(); return services; } // 注册 DbContext services.AddDbContext(options => { AppDbContext.ConfigureProvider(options, config); }); // 注册数据库管理器 services.AddScoped>(); return services; } /// /// 根据 注册对应具体类型的 实现。 /// /// 服务集合。 /// 数据库配置。 /// 数据库提供程序未注册时抛出。 private static void AddProviderAppDataContext(this IServiceCollection services, DatabaseConfiguration config) { switch (config.Provider) { case DatabaseProvider.SQLite: services.AddDbContext(options => AppDbContext.ConfigureProvider(options, config)); break; case DatabaseProvider.SqlServer: services.AddDbContext(options => AppDbContext.ConfigureProvider(options, config)); break; case DatabaseProvider.PostgreSQL: services.AddDbContext(options => AppDbContext.ConfigureProvider(options, config)); break; case DatabaseProvider.MySQL: services.AddDbContext(options => AppDbContext.ConfigureProvider(options, config)); break; default: throw new NotSupportedException($"数据库提供程序 {config.Provider} 未注册。"); } } /// /// 初始化数据库(在应用启动时调用一次)。 /// public static IServiceProvider InitializeDatabase( this IServiceProvider serviceProvider, Action? seeder = null) where TContext : AppDbContext { using var scope = serviceProvider.CreateScope(); var dbManager = scope.ServiceProvider.GetRequiredService>(); // 同步等待初始化(启动时阻塞) dbManager.InitializeAsync(seeder).GetAwaiter().GetResult(); return serviceProvider; } } }