I'm running a .Net 8 console application in Azure as a container image on linux using .NET SDK (no dockerfile). The app consists in several hosted services.
When my app is stopping I need to handle graceful shutdown (persist a few items in a database).
Whenever I press the Stop button in the Azure portal at the container instance level, my app immediately stops. My hosted services have their methods StopASync
called, but the app is closed before the associated stopping logic can be completed.
I've tried to use IHostApplicationLifetime
with no success.
// Wait until the stopping logic is completed in every IHostedServices
// The 10 seconds are NOT honored
_applicationLifetime.ApplicationStopping.Register(async () => await Task.Delay(10_000));
How can I make it so the app is not immediately shutdown when I press the container instance Stop button in the Azure portal? Should another stopping method be used?
As mentioned in the comments it seems that it is not supported currently, which is highly surprising (how are we expected to run production workload without graceful shutdown ?!)
To workaroung the issue, I've added a dedicated controller in the app for this purpose (see below) which I call when I need to shutdown the app.
See also this post about exposing an endpoint from the container instance
[Route("[controller]")]
[ApiController]
public class ShutdownController
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
private readonly ILogger<ShutdownController> _logger;
public ShutdownController(IHostApplicationLifetime hostApplicationLifetime, ILogger<ShutdownController> logger)
{
_hostApplicationLifetime = hostApplicationLifetime;
_logger = logger;
}
[HttpGet]
public async Task<string> Get()
{
_logger.LogInformation("Shutdown requested");
_hostApplicationLifetime.StopApplication();
return "Application shut down requested";
}
}