How-To: Get Started with Hosting
Hosting can be used to register services that will be accessible throughout the application via dependency injection (DI). This tutorial will walk you through the critical steps needed to leverage hosting in your application.
Important
This guide assumes you used the template wizard or dotnet new unoapp to create your solution. If not, it is recommended that you follow the Creating an application with Uno.Extensions documentation to create an application from the template.
Step-by-step
1. Installation
Add
Hostingto the<UnoFeatures>property in the Class Library (.csproj) file. If you already haveExtensionsin<UnoFeatures>, thenHostingis already installed, as its dependencies are included with theExtensionsfeature.<UnoFeatures> Material; + Hosting; Toolkit; MVUX; </UnoFeatures>
2. Create and Configure IApplicationBuilder
We need to expose the
IHostinstance to the rest of App.cs. Add the following property to your class file:private IHost Host { get; set; }The
IHosttype is defined in theMicrosoft.Extensions.Hostingnamespace. Since this and other related types will be used throughout this guide, it's recommended to add this namespace to yourGlobalUsings.csfile for convenience and cleaner code.global using Microsoft.Extensions.Hosting;As soon as your app is launched, use the
CreateBuilder()extension method to instantiate anIApplicationBuilderfrom yourApplicationobject:protected override void OnLaunched(LaunchActivatedEventArgs e) { var appBuilder = this.CreateBuilder(args) .Configure(host => { // Configure the host builder }); ... }
3. Set Up the Main Window with the Builder
Replace
MainWindow = new Window()or anyMainWindowassignment with thebuilderapproach:protected override void OnLaunched(LaunchActivatedEventArgs e) { var appBuilder = this.CreateBuilder(args) .Configure(host => { // Configure the host builder }); MainWindow = builder.Window; ... }
4. Build the IHost
Finally, build the host and assign it to the
Hostproperty:protected override void OnLaunched(LaunchActivatedEventArgs e) { var appBuilder = this.CreateBuilder(args) .Configure(host => { // Configure the host builder }); MainWindow = builder.Window; Host = appBuilder.Build(); ... }