ASP.NET Core interface IHostApplicationLifetime
allows developers to subscribe their handlers to ApplicationStarted, ApplicationStopping and ApplicationStopped events
ASP.NET Core provides developers with an IHostedService
interface that has StartAsync
and StopAsync
methods that are executed when the application starts and stops. This interface is typically used to trigger long running background tasks, but StartAsync
itself must return quickly so as not to block other hosted services, if any.
public class EInvoiceSenderService: IHostedService { private readonly ILogger logger; private readonly IHostApplicationLifetime appLifetime; public EInvoiceSenderService( ILogger<LifetimeEventsHostedService> logger, IHostApplicationLifetime appLifetime) { //<--- INJECTED DEPENDENCY this.logger = logger; this.appLifetime = appLifetime; } 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() { logger.LogInformation("OnStarted has been called."); // Perform post-startup activities here } private void OnStopping() { logger.LogInformation("OnStopping has been called."); // Perform on-stopping activities here } private void OnStopped() { logger.LogInformation("OnStopped has been called."); // Perform post-stopped activities here } }
Program.cs
builder.Services.AddHostedService<EInvoiceSenderService>();
References
https://levelup.gitconnected.com/3-ways-to-run-code-once-at-application-startup-in-asp-net-core-bcf45a6b6605
https://stackoverflow.com/questions/59650230/how-to-get-and-inject-the-ihostapplicationlifetime-in-my-service-to-the-containe