重构项目结构,引入 Avalonia-Common、Avalonia-EFCore、Avalonia-Services,实现 API 与桌面端统一端点注册、过滤器、鉴权和标准响应格式。支持多数据库自动迁移与配置,集成 Serilog 日志系统。移除旧路由与控制器,提升接口一致性与可维护性。
52 lines
1.7 KiB
C#
52 lines
1.7 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Avalonia_EFCore.Database
|
|
{
|
|
/// <summary>
|
|
/// 数据库服务注册扩展 —— 在 Program.cs 中一行配置数据库。
|
|
/// </summary>
|
|
public static class DatabaseExtensions
|
|
{
|
|
/// <summary>
|
|
/// 注册数据库上下文及相关服务。
|
|
/// </summary>
|
|
/// <typeparam name="TContext">继承自 AppDbContext 的业务 DbContext</typeparam>
|
|
public static IServiceCollection AddAppDatabase<TContext>(
|
|
this IServiceCollection services,
|
|
DatabaseConfiguration config)
|
|
where TContext : AppDbContext
|
|
{
|
|
// 注册配置
|
|
services.AddSingleton(config);
|
|
|
|
// 注册 DbContext
|
|
services.AddDbContext<TContext>(options =>
|
|
{
|
|
AppDbContext.ConfigureProvider(options, config);
|
|
});
|
|
|
|
// 注册数据库管理器
|
|
services.AddScoped<DatabaseManager<TContext>>();
|
|
|
|
return services;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 初始化数据库(在应用启动时调用一次)。
|
|
/// </summary>
|
|
public static IServiceProvider InitializeDatabase<TContext>(
|
|
this IServiceProvider serviceProvider,
|
|
Action<TContext, IServiceProvider?>? seeder = null)
|
|
where TContext : AppDbContext
|
|
{
|
|
using var scope = serviceProvider.CreateScope();
|
|
var dbManager = scope.ServiceProvider.GetRequiredService<DatabaseManager<TContext>>();
|
|
|
|
// 同步等待初始化(启动时阻塞)
|
|
dbManager.InitializeAsync(seeder).GetAwaiter().GetResult();
|
|
|
|
return serviceProvider;
|
|
}
|
|
}
|
|
}
|