I have experience building Windows Services in .NET Framework 4.6 and Visual Studio 2017 – depending on the business logic complexity, they are really easy. I’m writing a new Window Service and, moving with the times, I’m writing it in .NET 6 and Visual Studio 2022. I’m using the approved method in the Window Service template of inheriting from BackgroundService
. My problem is that I can’t catch the OnShutdown event from the Service Controller when the server is shutting down or rebooting. The BackgroundService
class includes StartAsync
and StopAsync
, but nothing for Shutdown.
Is there a way I can handle the server shutdown event using the BackgroundService
?
This is very important to me as I need a way to shut down my service gracefully when the server reboots.
I found a way to ‘cheat’ – I created a Console app and installed Core.System.ServiceProcess
from NuGet and then inherited from System.ServiceProcess.ServiceBase
instead in a class I created for the service. Then I could just override OnStart
, OnStop
, and OnShutdown
as usual. However, I’d rather use the BackgroundService
instead if possible.