Home

Awesome

Logo

Hosting Build status codecov NuGet version API docs

.NET Generic Host support for UI applications.

Usage (WPF)

Afer installing the NuGet package, add a Main method to your application component (commonly called App.xaml):

[STAThread]
private static void Main()
{
	var hostBuilder = Host.CreateApplicationBuilder();
	hostBuilder.Services.AddWpfApplication<App>();
	var host = hostBuilder.Build();
	host.RunWpfApplication<App>();
}

Next, disable the WPF-provided Main method.

For SDK-style WPF apps, set EnableDefaultApplicationDefinition to false in your project's properties.

For .NET Framework WPF apps, change the build tool for your application component (usually App.xaml) from Application to Page.

The .NET Generic Host and WPF Lifetime

The .NET Generic Host will shut down when the WPF application exits. Also, when the .NET Generic Host shuts down, it will request the WPF application to exit.

So, your application can exit the WPF application normally (e.g., Application.Current.Shutdown()), or it can request a shutdown via the .NET Generic Host (e.g., IHostApplicationLifetime.StopApplication()). Either of these will shut down the application cleanly.

Using the .NET Generic Host

You can modify the Main method to:

This project provides nothing fancy like automatically injecting ViewModels into Views, or Views for ViewModels. The exact way you use DI is up to you; this project just provides the .NET Generic Host with a lifetime compatible with UI applications.

Advanced Startup

AddWpfApplication<App> does two things:

If you need to customize the creation of your App instance, you can do both of the above yourself:

[STAThread]
private static void Main()
{
	var hostBuilder = Host.CreateApplicationBuilder();
	hostBuilder.Services.AddSingleton<IHostLifetime, WpfApplicationLifetime<App>>();
	hostBuilder.Services.AddSingleton<App>(provider =>
	{
		// Add any custom initialization work to this method.
		var app = new App();
		app.InitializeComponent();
		return app;

		// Do not call App.Run() - RunWpfApplication<App> will call App.Run().
	});
	var host = hostBuilder.Build();
	host.RunWpfApplication<App>();
}