本文主要是介绍用Microsoft.Extensions.Hosting 管理WPF项目.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先引入必要的包:
<ItemGroup><PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" /><PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /><PackageReference Include="Serilog" Version="4.0.0" /><PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" /><PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" /><PackageReference Include="Serilog.Sinks.File" Version="6.0.0" /></ItemGroup>
将app.xaml 的属性-生成操作改为"页"
此时弹出:
点击"取消"
点击显示所有文件, 将app.xaml包含在项目中
此时, 在csproj中,
<ItemGroup><ApplicationDefinition Remove="App.xaml" /></ItemGroup><ItemGroup><Page Include="App.xaml" /></ItemGroup>
在app.xaml.cs中 写入
public partial class App : Application{[STAThread]static void Main(string[] args){var app = new App();app.InitializeComponent();app.Run();}}
点击运行, 此时项目已经可以运行起来了
在app.xaml中 删除
StartupUri="MainWindow.xaml"
改为
<Application x:Class="HoistWpfTest.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:HoistWpfTest"><Application.Resources></Application.Resources>
</Application>
[STAThread]static void Main(string[] args){using var host = CreateHostBuilder(args).Build();host.Start();var app = new App();app.InitializeComponent();app.MainWindow = host.Services.GetRequiredService<MainWindow>();//app.MainWindow.Show();app.MainWindow.Visibility = Visibility.Visible;app.Run();}private static IHostBuilder CreateHostBuilder(string[] args){return Host.CreateDefaultBuilder(args).ConfigureServices(services =>{services.AddSingleton<MainWindow>();});}
此时 已经用Host管理了wpf项目.
较为完整的配置:
public partial class App : Application{[STAThread]static async void Main(string[] args){using var host = CreateHostBuilder(args).Build();await host.StartAsync();var app = new App();app.InitializeComponent();app.MainWindow = host.Services.GetRequiredService<MainView>();//app.MainWindow.Show();app.MainWindow.Visibility = Visibility.Visible;app.Run();}private static IHostBuilder CreateHostBuilder(string[] args){return Host.CreateDefaultBuilder(args).ConfigureServices(services =>{services.AddSingleton<MainViewModel>();services.AddSingleton(sp => new MainView{DataContext = sp.GetRequiredService<MainViewModel>()});services.AddSingleton<WeakReferenceMessenger>();services.AddSingleton<IMessenger, WeakReferenceMessenger>(sp =>sp.GetRequiredService<WeakReferenceMessenger>());services.AddSingleton(_ => Current.Dispatcher);}).ConfigureLogging(logging =>{logging.ClearProviders();Log.Logger = new LoggerConfiguration()//.WriteTo.Console().WriteTo.File("log.txt", rollingInterval: RollingInterval.Day).CreateLogger();logging.AddSerilog(Log.Logger);});}}
这篇关于用Microsoft.Extensions.Hosting 管理WPF项目.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!