DEV Community

Cover image for HostBuilder and Host for Windows App SDK
The Sharp Ninja
The Sharp Ninja

Posted on

HostBuilder and Host for Windows App SDK

Please visit the discussion on GitHub to weigh in.

@michael-hawker asked me to post this for community feedback.

I have created a HostBuilder and Host for Windows App SDK Desktop applications. The repository is at sharpninja/WindowsAppSdkHost and includes the complete WindowsAppSdkHost and WindowsAppSdkHostBuilder implementations which are based on the Microsoft.Extensions.Hosting.HostBuilder and Microsoft.Extensions.Hosting.Internal.Host implementations by Microsoft. The repository contains a complete Desktop application that references and uses both the builder and host.

What does it do?

Allows hosting a Windows App SDK Application in an IHost that manages the lifecycle of the hosted Application.


(Convert existing project or the default template's output)

  1. Add <DefineConstants>DISABLE_XAML_GENERATED_MAIN</DefineConstants> in the main PropertyGroup of your applications project file.
  2. Add reference to CommunityToolkit.Extensions.Hosting.WindowsAppSdk
  3. Add Program.cs to the root of your application project.
  4. Add this code to the Program.cs:
public static class Program
    public static Task Main(string[] args)
        var builder = new WindowsAppSdkHostBuilder<App>();

            (_, collection) =>
                // If your main Window is named differently, change it here.

        var app = builder.Build();

        return app.StartAsync();
Enter fullscreen mode Exit fullscreen mode
  1. Set your Program.cs as the startup object by adding <StartupObject>HostedWindowsAppSdk.Program</StartupObject> to your project file.
  2. Use the CancelableApplication as the base class of your application by modifying your App.xaml:
Enter fullscreen mode Exit fullscreen mode
  1. Update your App.xaml.cs to use dependency injection.
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
    // Get window from Dependency Injection.
    _mWindow = Services.GetRequiredService<MainWindow>();

Enter fullscreen mode Exit fullscreen mode


The WindowsAppSdkHost uses several features of the Microsoft.Extensions ecosystem:

  1. Includes all configuration resources defined for the DefaultHostBuilder.
  2. Registers the required CancellableApplication with dependency injection.
  3. Manages the lifecycle of the Application in the StartAsync method of the WindowsAppSdkHost.
  4. Write unhandled errors to default ILogger. The Ilogger can be obtained from the static Services property of the CancellableApplication after building the app.


I need help getting the project template formatted correctly for dotnet new.

Discussion (0)