A simple helper to perform async application initialization in .NET Core 2.0 or higher.
-
Install the Barney.WaitForIt NuGet package:
Command line:
dotnet add package Barney.WaitForIt
Package manager console:
Install-Package Barney.WaitForIt
-
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 = new HostBuilder() .ConfigureServices(configureServices) .UseConsoleLifetime() .Build(); await host.WaitForItAsync(); await host.StartAsync(); }
(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.