Asynchronous initialization in ASP.NET Core with custom middleware
Update: I no longer recommend the approach described in this post. I propose a better solution here: Asynchronous initialization in ASP.NET Core, revisited.
Sometimes you need to perform some initialization steps when your web application starts. However, putting such code in the Startup.Configure method is generally not a good idea, because:
There’s no current scope in the Configure method, so you can’t use services registered with “scoped” lifetime (this would throw an InvalidOperationException: Cannot resolve scoped service ‘MyApp.