using MembranePoreTester.Communication; using Microsoft.Extensions.Configuration; using OfficeOpenXml; using System; using System.IO; using System.Windows; namespace MembranePoreTester { public partial class App : Application { public static IPlcService PlcService { get; private set; } public static PlcConfiguration PlcConfig { get; private set; } protected async override void OnStartup(StartupEventArgs e) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; base.OnStartup(e); using var db = new AppDbContext(); db.Database.EnsureCreated(); // 自动建表 var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); var configuration = builder.Build(); PlcConfig = configuration.GetSection("PlcSettings").Get(); if (PlcConfig == null) throw new InvalidOperationException("PLC settings missing in appsettings.json"); PlcService = new ModbusTcpPlcService(PlcConfig); var plcService = App.PlcService as ModbusTcpPlcService; try { await plcService.EnsureConnectedAsync(); } catch (Exception ex) { MessageBox.Show($"PLC 连接失败:{ex.Message}"); } } protected override void OnExit(ExitEventArgs e) { (PlcService as IDisposable)?.Dispose(); base.OnExit(e); } } }