Created
January 19, 2021 04:11
-
-
Save mirsaeedi/b84f9eef2402bb47eab153368268cfaf to your computer and use it in GitHub Desktop.
ASP.NET Lifetime Event Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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