Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kestrel shutdown function in Startup.cs in ASP.NET Core

Is there a shutdown function when using Microsoft.AspNet.Server.Kestrel? ASP.NET Core (formerly ASP.NET vNext) clearly has a Startup sequence, but no mention of shutdown sequence and how to handle clean closure.

like image 908
Fahad Avatar asked Feb 07 '16 18:02

Fahad


3 Answers

In ASP.NET Core you can register to the cancellation tokens provided by IApplicationLifetime

public class Startup 
{
    public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime) 
    {
        applicationLifetime.ApplicationStopping.Register(OnShutdown);
    }

    private void OnShutdown()
    {
         // Do your cleanup here
    }
}

IApplicationLifetime is also exposing cancellation tokens for ApplicationStopped and ApplicationStarted as well as a StopApplication() method to stop the application.

For .NET Core 3.0+

From comments @Horkrine

For .NET Core 3.0+ it is recommended to use IHostApplicationLifetime instead, as IApplicationLifetime will be deprecated soon. The rest will still work as written above with the new service

like image 185
Tseng Avatar answered Oct 06 '22 11:10

Tseng


In addition to the original answer, I had an error while trying to wire the IApplicationLifetime within the constructor.

I solved this by doing:

public class Startup 
{
    public void Configure(IApplicationBuilder app) 
    {
        var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
        applicationLifetime.ApplicationStopping.Register(OnShutdown);
    }

    private void OnShutdown()
    {
         // Do your cleanup here
    }
}
like image 32
Stefan Hendriks Avatar answered Oct 06 '22 13:10

Stefan Hendriks


This class is now obsolete, please refer to the new interface IHostApplicationLifetime. More info here.

like image 3
hamiltonjose Avatar answered Oct 06 '22 13:10

hamiltonjose