Skip to content

Instantly share code, notes, and snippets.

@mirsaeedi
Created January 19, 2021 04:11
Show Gist options
  • Save mirsaeedi/b84f9eef2402bb47eab153368268cfaf to your computer and use it in GitHub Desktop.
Save mirsaeedi/b84f9eef2402bb47eab153368268cfaf to your computer and use it in GitHub Desktop.
ASP.NET Lifetime Event Handler
internal class LifetimeEventsHostedService : IHostedService
{
private readonly ILogger<LifetimeEventsHostedService> _logger;
private readonly IHostApplicationLifetime _appLifetime;
private readonly TelemetryClient _telemtryClient;
public LifetimeEventsHostedService(
ILogger<LifetimeEventsHostedService> logger,
IHostApplicationLifetime appLifetime,
TelemetryClient telemtryClient)
{
_logger = logger;
_appLifetime = appLifetime;
_telemtryClient = telemtryClient;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
_appLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
}
private void OnStopping()
{
_logger.LogInformation("OnStopping has been called.");
_telemtryClient.Flush();
}
private void OnStopped()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment