Search code examples
.netwindows-services

Detect if code is running as a service


Is there a way for an .NET library to detect whether or not it is being run as a service?

My library can be run either way. But when its run as a service, developers need to call an additional method indicating that fact or certain features won't work correctly. I want my library, which handles logging, to write a warning if it is used in a service without that method being called.


Solution

  • You can add the Microsoft.Extensions.Hosting.WindowsServices NuGet package and use the WindowsServiceHelpers.IsWindowsService() helper method.

    For Linux you can use Microsoft.Extensions.Hosting.Systemd and the SystemdHelpers.IsSystemdService() method.