Recipe 14.3 · C#
Running as a Windows Service
Problem
The job must run on a Windows server, start at boot, run under a low-privilege account and restart
if it fails. The old way meant a ServiceBase subclass, an installer class and InstallUtil.exe,
and a service that could not be run from the command line for debugging.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: separate code paths for service and console
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
var service = new SyncService();
service.DebugStart(args); // hand-written test hook
Console.ReadLine();
service.DebugStop();
}
else
{
ServiceBase.Run(new SyncService());
}
}
The improved recipe
Reference Microsoft.Extensions.Hosting.WindowsServices and call AddWindowsService. The same
executable runs as a console app when you start it from a terminal or Visual Studio and as a
Windows Service when the Service Control Manager starts it.
// Program.cs
using System;
using ImproveCode.Jobs;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
const string ServiceName = "InvoiceSync";
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options =>
{
options.ServiceName = ServiceName;
});
builder.Services.AddTimedJob<InvoiceSyncJob>(TimeSpan.FromMinutes(5));
IHost host = builder.Build();
await host.RunAsync();
Configuration for the event log in appsettings.json, so only warnings and errors go there:
{
"Logging": {
"LogLevel": { "Default": "Information" },
"EventLog": {
"LogLevel": { "Default": "Warning" }
}
}
}
Publish and install from an elevated PowerShell prompt:
dotnet publish -c Release -r win-x64 --self-contained false `
-o C:\Services\InvoiceSync
New-EventLog -LogName Application -Source InvoiceSync
New-Service -Name InvoiceSync `
-DisplayName "ImproveCode Invoice Sync" `
-BinaryPathName "C:\Services\InvoiceSync\InvoiceSync.exe" `
-StartupType Automatic
sc.exe config InvoiceSync obj= "NT SERVICE\InvoiceSync"
sc.exe failure InvoiceSync reset= 86400 `
actions= restart/60000/restart/60000/none/0
sc.exe failureflag InvoiceSync 1
Start-Service InvoiceSync
How it works
AddWindowsService checks at start-up whether the process was launched by the Service Control
Manager. If it was, it replaces the default console lifetime with a Windows Service lifetime that
reports start and stop to the SCM and turns a stop request into the same stoppingToken
cancellation that Ctrl+C triggers in a console. If it was not, it does nothing. There is one code
path, and you debug the service by pressing F5.
It also fixes the classic content-root problem. Services start with C:\Windows\System32 as the
current directory, so appsettings.json was not found and relative paths wrote into the system
folder. Under the Windows Service lifetime the content root is set to the folder that holds the
executable. It also adds the Windows event log as a logging provider. The event source defaults to
the application name, which for a project called InvoiceSync is InvoiceSync.
The event source must exist before a low-privilege account can write to it, which is why the
install script creates it with New-EventLog while you are elevated.
NT SERVICE\InvoiceSync is a virtual account. Windows manages its password, it has minimal rights
on the local machine, and you can grant it access to a folder or a SQL Server login by that name.
It is a much better default than LocalSystem or a shared domain account whose password is in a
spreadsheet.
The sc.exe failure line sets recovery actions: restart after 60 seconds on the first and second
failure, and do nothing after that, with the counter reset daily. failureflag 1 applies those
actions when the service stops with an error, not only when the process crashes.
Variations and pitfalls
- Fatal errors and recovery. The timed service in Recipe 14.1 logs and continues, which is
right for one bad run. For a failure the service cannot recover from, such as a missing
database, Microsoft's guidance for workers is to log it and end the process with
Environment.Exit(1). The non-zero exit code is what triggers the recovery actions. - Self-contained or framework-dependent.
--self-contained falseneeds the .NET runtime on the server. A self-contained publish carries its own runtime, which you then patch yourself. - Linux. The same program runs under systemd with the
Microsoft.Extensions.Hosting.Systemdpackage andbuilder.Services.AddSystemd(). Both calls can sit side by side, and each does nothing on the other platform.