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)
- Add
<DefineConstants>DISABLE_XAML_GENERATED_MAIN</DefineConstants>in the mainPropertyGroupof your applications project file. - Add reference to
CommunityToolkit.Extensions.Hosting.WindowsAppSdk - Add
Program.csto the root of your application project. - Add this code to the
Program.cs:
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
var builder = new WindowsAppSdkHostBuilder<App>();
builder.ConfigureServices(
(_, collection) =>
{
// If your main Window is named differently, change it here.
collection.AddSingleton<MainWindow>();
}
);
var app = builder.Build();
app.StartAsync().GetAwaiter().GetResult();
}
}- Set your
Program.csas the startup object by adding<StartupObject>HostedWindowsAppSdk.Program</StartupObject>to your project file. - Use the
CancelableApplicationas the base class of your application by modifying yourApp.xaml:
<host:CancelableApplication
x:Class="HostedWindowsAppSdk.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:host="using:CommunityToolkit.Extensions.Hosting"
xmlns:local="using:HostedWindowsAppSdk">
<Application.Resources>
</Application.Resources>
</host:CancelableApplication>- 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>();
_mWindow.Activate();
}The WindowsAppSdkHost uses several features of the Microsoft.Extensions ecosystem:
- Includes all configuration resources defined for the
DefaultHostBuilder. - Registers the required
CancellableApplicationwith dependency injection. - Manages the lifecycle of the Application in the
StartAsyncmethod of theWindowsAppSdkHost. - Write unhandled errors to default
ILogger. TheIloggercan be obtained from the staticServicesproperty of theCancellableApplicationafter building the app.
If there are other patterns you feel should be available or required then start a discussion.