Where to put code to run after startup is completed

Since .net core 2.0, you should probably implement your own IHostedService. Each registered IHostedService will be started in the order they were registered. If they fail, they can cause the host to fail to start.

Since you wish to perform database operations, you should also create a new service scope to control the lifetime of your database connection.

public class StartupService : IHostedService{
    private IServiceProvider services;
    public StartupService(IServiceProvider services){
        this.services = services;
    }
    
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        using var scope = serviceProvider.CreateScope();
        using var context = scope.ServiceProvider.GetRequiredService<...>();
        ... do work here
    }
}

// then in configure services
services.AddHostedService<StartupService>();

Note that EF Core 5 introduces IDbContextFactory, which could be used to create a context outside of any DI service scope.

Each of the other answers to this question will run while the web server is being configured, which is also executed within an IHostedService.


Or use IStartupFilter.

This is mainly for configuring middleware, but should allow you to perform actions after the configuration is over.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-2.1#extend-startup-with-startup-filters


Probably the best place is in Configure method after UseMvc() call. That is also the place where you usually apply migrations. You can add as many classes that DI knows as parameter.
For example:

public void Configure(IApplicationBuilder app)

or

public void Configure(IApplicationBuilder app, AppUserManager userManager, IServiceProvider serviceProvider)

or

public void Configure(IApplicationBuilder app, MyDbContext context)

If you want to check this in background (only if you don't care about result - application should run also if verification fails), check my answer here.
Also this answer may help you.

Tags:

Asp.Net Core