/Extensions.Hosting.AsyncInitialization

Async initialization in .NET Core generic host (.NET Core 2.1+ and ASP.NET Core 3)

Primary LanguageC#Apache License 2.0Apache-2.0

Extensions.Hosting.AsyncInitialization

NuGet version AppVeyor build AppVeyor tests

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.

Usage

  1. Install the Extensions.Hosting.AsyncInitialization NuGet package:

    Command line:

    dotnet add package Extensions.Hosting.AsyncInitialization

    Package manager console:

    Install-Package Extensions.Hosting.AsyncInitialization
  2. 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
        }
    }
  3. Register your initializer(s) in the same place as other services:

        services.AddAsyncInitializer<MyAppInitializer>();
  4. 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();
    }

(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.