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
.