ASP.NET Core application shutdown events
While porting an existing library to ASP.NET Core I had to find the equivalent functionality of IRegisteredObject which I use for graceful shutdowns of running tasks in background threads. The newer & nicer approach to this in ASP.NET Core is Microsoft.AspNetCore.Hosting.IApplicationLifetime:
/// <summary> /// Allows consumers to perform cleanup during a graceful shutdown. /// </summary> public interface IApplicationLifetime { /// <summary> /// Triggered when the application host has fully started and is about to wait /// for a graceful shutdown. /// </summary> CancellationToken ApplicationStarted { get; } /// <summary> /// Triggered when the application host is performing a graceful shutdown. /// Requests may still be in flight. Shutdown will block until this event completes. /// </summary> CancellationToken ApplicationStopping { get; } /// <summary> /// Triggered when the application host is performing a graceful shutdown. /// All requests should be complete at this point. Shutdown will block /// until this event completes. /// </summary> CancellationToken ApplicationStopped { get; } /// <summary>Requests termination the current application.</summary> void StopApplication(); }
Unlike the old IRegisteredObject this interface is pretty clear on it’s functionality.
Registering a method to be called for any of the three operations is simple:
//register the application shutdown handler applicationLifetime.ApplicationStopping.Register(DisposeResources); protected void DisposeResources() { //Cleanup stuff when the app is shutting down }
Obtaining an instance of IApplicationLifetime can be done during Startup.cs in the Configure method
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime) { // start your app }
Happy coding!
comments powered by Disqus