UseWindowsService() adds Windows Service integration to a .NET worker service through IHostBuilder. During development or console execution, it does nothing, so the application behaves normally while gaining the hooks required for service installation. section 34.2.2
Enable and install the integration with these practical steps:
- Add the Microsoft.Extensions.Hosting.WindowsServices NuGet package. section 34.2.2
- Call UseWindowsService() on the IHostBuilder while configuring the worker normally. section 34.2.2
- Publish the application, then run the Windows sc utility from an Administrator command prompt with the published executable path. section 34.2.2
- Manage startup, shutdown, service identity, and error handling through the Windows Services control panel. section 34.2.2
Listing 34.9 Adding Windows Service support to a worker service
IHost host = Host.CreateDefaultBuilder(args) #1 .ConfigureServices((hostContext, services) => #1 { #1 Services.AddHostedService<Worker>(); #1 }) #1 .UseWindowsService() #2 .Build(); host.Run(); #1 Configures your worker service as you would normally #2 Adds support for running as a Windows Service.
Shows the minimal host configuration, including the normal hosted worker registration and the UseWindowsService() call. section 34.2.2
