When running an ASP.NET Core web application, there are cases when you need to do some logic when the application stops. An example: you are logging and have to flush the last message to the log (Application Insights). In that case you need can add an event in the Configure
method. In this post I show a short example of how doing this.
Register the Shutdown event
The Configure
in the Startup
class can have the following parameters:
IApplicationBuilder
IHostingEnvironment
ILoggerFactory
IApplicationLifetime
In the IApplicationLifetime
interface you can register an event that is triggered when the application stops:
public class Startup { public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime) { applicationLifetime.ApplicationStopping.Register(OnShutdown); } private void OnShutdown() { //this code is called when the application stops } }
The OnShutdown
method is now wired to run when the application stops.
Apply to Application Insights
By default Application Insights buffers messages to send them in bulk to the server. When you do not flush your log, the chance is that you miss messages when your application is terminates. To solve this you need to flush buffer:
public class Startup { private TelemetryClient _telemetryClient; public Startup(IHostingEnvironment env) { ... _telemetryClient = new TelemetryClient() { InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"], }; ... } public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime) { applicationLifetime.ApplicationStopping.Register(OnShutdown); ... } private void OnShutdown() { _telemetryClient.Flush(); //Wait while the data is flushed System.Threading.Thread.Sleep(1000); } }
With these few lines of code, you will not miss any of you important logging messages in the future.
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