修改App.xaml.cs 重新OnStartup和OnExit方法 并使用Host启动 解析appsettings.json配置文件
在App.xaml中删除StartUri属性,否则会启动多个MainWindow
包引用信息如下:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting
/// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : System.Windows.Application { public static IHost? AppHost { get; private set; } public IConfiguration Configuration { get; private set; } public App() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); Configuration = builder.Build(); AppHost = Host.CreateDefaultBuilder() .ConfigureServices((hostContext, services) => { services.AddDbContext<PackingDbContext>(option => { var connectionString = Configuration.GetConnectionString("Mysql"); var serverVersion = ServerVersion.AutoDetect(connectionString); option.UseMySql(connectionString, serverVersion, p => p.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)); //移除外键 option.ReplaceService<IMigrationsModelDiffer, MigrationsModelDifferWithoutForeignKey>(); }); services.AddScoped<MainWindow>(); services.AddSingleton(Configuration); //注册分布式Id生成器 services.AddSnowflake(Configuration); //注册AutoMapper services.AddAutoMapper(cfg => { cfg.AddProfile<PackingMapperProfile>(); }); //services inject var injectName = typeof(IService).Name; var injectTypes = Assembly.Load("Application").GetTypes().Where(p => p.IsClass); foreach (var t in injectTypes) { if (t.GetInterface(injectName) != null) services.AddScoped(t); } }).Build(); } protected override async void OnStartup(StartupEventArgs e) { await AppHost!.StartAsync(); var startUp = AppHost.Services.GetRequiredService<MainWindow>(); startUp.Show(); base.OnStartup(e); } protected override async void OnExit(ExitEventArgs e) { await AppHost!.StopAsync(); base.OnExit(e); } }
标签:AppHost,依赖,App,var,Extensions,services,WPF,Configuration,注入 From: https://www.cnblogs.com/mwtsai/p/17317291.html