Search code examples
asp.net-coregraceful-degradation

graceful shutdown asp.net core


Coming across very outdated information on graceful shutdown of the asp.net core application, can someone fill in with the updated info.

Usecase: I'd like to unregister with consul on application exit.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((host, config) =>
        {
        })
        .UseStartup<Service>();

Solution

  • For capturing graceful shutdown, you could try IHostApplicationLifetime.

    // Copyright (c) .NET Foundation. All rights reserved.
    // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
    
    using System.Threading;
    
    namespace Microsoft.Extensions.Hosting
    {
        /// <summary>
        /// Allows consumers to be notified of application lifetime events. This interface is not intended to be user-replaceable.
        /// </summary>
        public interface IHostApplicationLifetime
        {
            /// <summary>
            /// Triggered when the application host has fully started.
            /// </summary>
            CancellationToken ApplicationStarted { get; }
    
            /// <summary>
            /// Triggered when the application host is performing a graceful shutdown.
            /// Shutdown will block until this event completes.
            /// </summary>
            CancellationToken ApplicationStopping { get; }
    
            /// <summary>
            /// Triggered when the application host is performing a graceful shutdown.
            /// Shutdown will block until this event completes.
            /// </summary>
            CancellationToken ApplicationStopped { get; }
    
            /// <summary>
            /// Requests termination of the current application.
            /// </summary>
            void StopApplication();
        }
    }
    

    A demo:

    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        var life = host.Services.GetRequiredService<IHostApplicationLifetime>();
        life.ApplicationStopped.Register(() => {
            Console.WriteLine("Application is shut down");
        });
        host.Run();
    }