using System.CommandLine; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Gpulse.WCT.DataAnalyzer.Commands; using Gpulse.WCT.DataAnalyzer.Core.Data; using Gpulse.WCT.DataAnalyzer.Core.Extensions; using Gpulse.WCT.DataAnalyzer.Core.Services; namespace Gpulse.WCT.DataAnalyzer; /// /// Gpulse.WCT.DataAnalyzer - 无线充电FOD日志数据采集系统 /// public class Program { public static async Task Main(string[] args) { // 1. 构建引导配置(用于 Serilog 初始化) var bootstrapConfig = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build(); // 2. 创建引导日志器 Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(bootstrapConfig) .Enrich.FromLogContext() .CreateBootstrapLogger(); try { var builder = Host.CreateApplicationBuilder(args); // 3. 使用 AddConfiguration 添加已构建的配置(关键修复) builder.Configuration.AddConfiguration(bootstrapConfig); // 4. 配置 Serilog builder.Services.AddSerilog((_, loggerConfig) => { loggerConfig .ReadFrom.Configuration(builder.Configuration) .Enrich.FromLogContext(); }); // 5. 注册服务 builder.Services.AddDatabaseServices(builder.Configuration); builder.Services.AddApplicationServices(); var app = builder.Build(); // 初始化数据库 using (var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); // 种子数据 SeedData.Initialize(dbContext); } // 创建 CLI 命令 using var commandScope = app.Services.CreateScope(); var provider = commandScope.ServiceProvider; var rootCommand = new RootCommand("Gpulse.WCT.DataAnalyzer - FOD Log Data Parser"); rootCommand.AddCommand(new ParseCommand(provider.GetRequiredService())); rootCommand.AddCommand(new StatsCommand(provider.GetRequiredService())); rootCommand.AddCommand(new ExportCommand(provider.GetRequiredService())); rootCommand.AddCommand(new CleanCommand(provider.GetRequiredService())); return await rootCommand.InvokeAsync(args); } catch (Exception ex) { Log.Fatal(ex, "Application terminated unexpectedly"); return 1; } finally { await Log.CloseAndFlushAsync(); } } }