In C# .NET 8, I have…
var builder = WebApplication.CreateBuilder(args);
builder
.RegisterSharedServices()
.Services
.AddSingleton<..., ...>();
// Add Controllers
builder
.AddCoreApiSupport() // that's custom
. ...();
// Host
builder
.Services
.AddHostedService<CoreBackgroundService>();
var webApp = builder.Build();
...
webApp.SetupApiSupport();
await webApp.RunAsync();
type of the project is <Project Sdk="Microsoft.NET.Sdk.Web">
.
So essentially I am running a BackgroundService
implementation with an API Support on top of it, in a Linux Docker Container.
I want to capture and handle the SIGTERM
signal, by the means of CancellationToken
which is propagated everywhere. Its “entry point” is here, in the implementation of the class deriving from BackgroundService
:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
It baffles me that stoppingToken
is never triggered (i.e. a Task.Delay(...)
wouldn’t throw an exception, for example. It seems like the signal is completely ignored, when I shut the container down from Docker Desktop. I’ve read something about requiring RunConsoleAsync
and a Console Lifetime Support
, which doesn’t make a lot of sense to me.
My question is – what do I need to change, so that my CancellationToken
gets triggered on Docker Container shut down?
I’ve tried this too:
appLifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine("Stopping!");
});
for what it’s worth, I never get the Console.WriteLine(...)
to execute. Not sure what that means, it’s like if the ApplicationStopping
event never triggers.
7