A simple helper to perform async application initialization for the generic host in .NET Core 2.1 or higher (including ASP.NET Core 3).
Note: ASP.NET Core 2.x doesn't use the generic host. If you need to perform async initialization in ASP.NET Core 2.x, use AspNetCore.AsyncInitialization instead.
-
Install the Extensions.Hosting.AsyncInitialization NuGet package:
Command line:
dotnet add package Extensions.Hosting.AsyncInitialization
Package manager console:
Install-Package Extensions.Hosting.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 same place as other services:
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 = CreateHostBuilder(args).Build(); await host.InitAsync(); await host.RunAsync(); }
(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.