Run Code Once at Application Startup in ASP.NET Core

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) {

        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