'How to use a generic HostBuilder in a UWP application
In my WPF applications I use a generic HostBuilder in this way:
public partial class App : Application
{
private readonly IHost _host;
public App()
{
_host = Host.CreateDefaultBuilder()
.ConfigureServices(services => { ConfigureServices(services); })
.Build();
}
private void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<MainWindow>();
// Add all services, viewmodels, etc..
}
protected async override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
await _host.StartAsync();
}
protected async override void OnExit(ExitEventArgs e)
{
using(_host)
{
await _host.StopAsync();
}
base.OnExit(e);
}
}
And in a UWP application:
sealed partial class App : Application
{
private readonly IHost _host;
public App()
{
this.InitializeComponent();
_host = Host.CreateDefaultBuilder()
.ConfigureServices(services => { ConfigureServices(services); })
.Build();
}
private void ConfigureServices(IServiceCollection services)
{
// Add all services, viewmodels, etc..
}
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
await _host.StartAsync();
}
}
The question:
Where/when should I stop the service?
using(_host)
{
await _host.StopAsync();
}
Solution 1:[1]
Where/when should I stop the service?
You need to know UWP life cycle, and OnSuspending
meet your scenario, it will be invoked when the user switches to another app or to the desktop, base on the the life cycle, it also be invoked when your close app.
So, if your builder need to stop when app turn into suspend state, you could use above event.
And if you only want to stop the build when app close, please use CloseRequested
event
SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += (s, p)=>{
// stop host here
};
Please note for use this event, you need to add confirmAppClose capability to your app manifest file.
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap mp rescap">
<rescap:Capability Name="confirmAppClose" />
Update
Derive from the document, the Host class looks only apply to .NET Platform Extensions, it does not coantain uwp.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |