.NET › Generic Host

How do you register configuration and services differently for a Worker Service running as a Windows Service or systemd daemon?

Intermediate

Answer

The Microsoft.Extensions.Hosting.WindowsServices and Microsoft.Extensions.Hosting.Systemd packages provide UseWindowsService() and UseSystemd() extension methods that configure the host to properly integrate with the respective OS service manager -- handling service-specific lifecycle events, logging redirection (to the Windows Event Log or systemd journal), and correct working directory resolution, which differ from running as a plain console application interactively.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options => options.ServiceName = "MyWorkerService");
builder.Services.AddSystemd();
builder.Services.AddHostedService<Worker>();

var host = builder.Build();
host.Run();  // automatically detects and adapts to the actual hosting context
Real-world example A Worker Service deployed as a Windows Service in one environment and as a systemd daemon on Linux in another uses both AddWindowsService and AddSystemd registrations simultaneously, with the host automatically detecting and adapting to whichever context it's actually running under.

Common follow-ups: What logging differences occur when running under systemd versus interactively?;How do you install and manage a .NET Worker Service as an actual Windows Service?