Awesome
AspNetCore.AsyncInitialization
A simple helper to perform async application initialization in ASP.NET Core 2.x.
Note: This project supports only ASP.NET Core 2.x. If you need to perform async initialization for the generic host (.NET Core 2.1+ and ASP.NET Core 3), use Extensions.Hosting.AsyncInitialization instead.
Usage
-
Install the AspNetCore.AsyncInitialization NuGet package:
Command line:
dotnet add package AspNetCore.AsyncInitialization
Package manager console:
Install-Package AspNetCore.AsyncInitialization
-
Create a class (or several) that implements
IAsyncInitializer
. This class can depend on any registered service.public class MyAppInitializer : IAsyncInitializer { public MyAppInitializer(IFoo foo, IBar bar) { ... } public async Task InitializeAsync() { // Initialization code here } }
-
Register your initializer(s) in the
Startup.ConfigureServices
method:services.AddAsyncInitializer<MyAppInitializer>();
-
In the
Program
class, make theMain
method async and change its code to initialize the host before running it:public static async Task Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); await host.InitAsync(); host.Run(); }
(Note that you need to set the C# language version to 7.1 or higher in your project to enable the "async Main" feature.)
This will run each initializer, in the order in which they were registered.