Application Shutdown in ASP.NET Core 6/8

In .NET 6 and 8, gracefully handling application shutdown is crucial for releasing resources or completing ongoing tasks before the application ends. The IApplicationLifetime interface was deprecated in favor of IHostApplicationLifetime in ASP.NET Core 3.0, and this approach continues in .NET 6/8.

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.

Unknown's avatar

Author: Peter Groenewegen

Hi, I’m Peter Groenewegen—a technologist, developer advocate, and AI enthusiast passionate about building tools that truly fit people’s workflows. My journey in tech has been one of innovation, collaboration, and a relentless curiosity to make the complex simple.

4 thoughts on “Application Shutdown in ASP.NET Core 6/8”

  1. 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?

    Liked by 1 person

    1. 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.

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.