Async initialization in .NET Core generic host (.NET Core 2.1+ and ASP.NET Core 3)
A simple helper to perform async application initialization for the generic host in .NET 6.0 or higher (e.g. in ASP.NET Core apps).
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(CancellationToken cancellationToken)
{
// Initialization code here
}
}
Register your initializer(s) in the same place as other services:
services.AddAsyncInitializer<MyAppInitializer>();
In the Program
class, make the Main
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();
}
You can also pass a CancellationToken
in order to propagate notifications to cancel the initialization if needed.
In the following example, the initialization will be cancelled when Ctrl + C
keys are pressed :
public static async Task Main(string[] args)
{
using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
// The following line will hook `Ctrl` + `C` to the cancellation token.
Console.CancelKeyPress += (source, args) => cancellationTokenSource.Cancel();
var host = CreateHostBuilder(args).Build();
await host.InitAsync(cancellationTokenSource.Token);
await host.RunAsync();
}
This will run each initializer, in the order in which they were registered.