1. Add IHostApplicationLifetime to your service
In modern ASP.NET Core applications, IHostApplicationLifetime is injected into services, such as controllers or services where you need to handle shutdown events.
public class ShutdownService
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
public ShutdownService(IHostApplicationLifetime hostApplicationLifetime)
{
_hostApplicationLifetime = hostApplicationLifetime;
}
public void ConfigureShutdownEvent()
{
_hostApplicationLifetime.ApplicationStopping.Register(OnShutdown);
}
private void OnShutdown()
{
// Code to clean up resources or log shutdown events
Console.WriteLine("Application is stopping...");
}
}
2. Configure IHostApplicationLifetime in Startup
While Program.cs is the new configuration file starting with .NET 6, IHostApplicationLifetime can be injected into services directly via dependency injection.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ShutdownService>();
}
public void Configure(IApplicationBuilder app, IHostApplicationLifetime hostApplicationLifetime)
{
var shutdownService = app.ApplicationServices.GetRequiredService<ShutdownService>();
shutdownService.ConfigureShutdownEvent();
app.Run();
}
}
3. Configure Graceful Shutdown in Program.cs
In .NET 6/8, applications are commonly built using the WebApplication builder in Program.cs. To configure shutdown handling, you can leverage the following approach:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ShutdownService>();
var app = builder.Build();
app.Lifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine("Application is stopping...");
// Place any cleanup or logging logic here
});
app.Run();
4. Using CancellationToken in Hosted Services
If you’re using a hosted service, you can also access the CancellationToken for finer control over when tasks are canceled during shutdown.
public class BackgroundService : IHostedService
{
private readonly ILogger<BackgroundService> _logger;
public BackgroundService(ILogger<BackgroundService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Background service is starting.");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Background service is stopping.");
return Task.CompletedTask;
}
}
5. Graceful Shutdown with Timeout
.NET 6/8 has built-in support for configuring graceful shutdown timeouts. You can set a timeout for application shutdown in Program.cs.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<BackgroundService>();
var app = builder.Build();
app.Lifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine("Application is stopping...");
});
app.Run();
// Set graceful shutdown timeout
builder.Host.ConfigureServices(services =>
{
services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(30); // Timeout in seconds
});
});
Conclusion
The update to .NET 6 and 8 simplifies the process of application shutdown while providing more control through IHostApplicationLifetime and cancellation tokens. This method is effective in managing cleanup and releasing resources before the application terminates.
By utilizing IHostApplicationLifetime, ApplicationStopping events can be handled efficiently, ensuring a smooth shutdown experience in modern ASP.NET Core applications.
Thanks for documenting the OnShutdown(). I was able to get it set up on my dotnet core 2.x Web API where I’m using akka.net.
LikeLiked by 2 people
The OnShutdown doesn’t get called in my case. I have an empty web api application on .net core 3.1.
But I’ve used IHostApplicationLifetime as IApplicationLifetime is obsolete.
Can someone help me?
LikeLiked by 1 person
I use ASP.NET Core 3.1 and it works just fine. In the above sample, simply change “IApplicationLifetime” to “IHostApplicationLifetime” and your are good to go.
LikeLike
Thanks for you comment. When I have time I’ll try to do an update.
LikeLike