Where to put your initialization steps in ASP.NET Core Web Api? Where to put your initialization steps in ASP.NET Core Web Api? docker docker

Where to put your initialization steps in ASP.NET Core Web Api?


To answer your question, I am giving an example for applying migration on startup. you can use the same concept.

public void ConfigureServices(IServiceCollection services){    services.AddDbContext<DataContext>(x => x.UseSqlite("Data Source=LocalDatabase.db"));    ...}

An instance of the EF Core DB Context service to be injected as a parameter into the Configure() method.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext){    // migrate any database changes on startup (includes initial db creation)    dataContext.Database.Migrate();    ...}


Found answer in link above. We can use IHostedService interface starting from .Net Core 3.0 especially for those tasks. Important note is that lower versions IS NOT SUITABLE, because they are not waiting StartAsync methods to complete before serving user requests:

internal sealed class Boot : IHostedService{   public Task StartAsync(CancellationToken token){       //migrate db or whatever here   }   public Task StopAsync(CancellationToken token){       //gracefull shutdown for 5 sec, after which token will blowup. It will still wait for method return.   }}

Then register it in your DI and Configure method:

    // This method gets called by the runtime. Use this method to add services to the container.    public void ConfigureServices(IServiceCollection services)    {        services.AddControllers();        services.AddSingleton<IBoot, Boot>();        services.AddHostedService(x=> x.GetService<IBoot>());    }

The pros:

  • No woo-doo magic with async wait in sync context. Everything async/cancellable, non-deadlocking.
  • It has gracefull shutdown, in case you hold some unmanaged or other resources in your initialization that needs to be disposed.
  • It has full support of Dependency Injection.

The cons:

  • StopAsync will not be invoked on exceptions. Be cautios, use Dispose too.
  • Watch for version of framework, accidental switch to lower version will cause you world of pain.