Skip to content

thomaslevesque/AspNetCore.AsyncInitialization

Repository files navigation

AspNetCore.AsyncInitialization

NuGet version AppVeyor build AppVeyor tests

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

  1. Install the AspNetCore.AsyncInitialization NuGet package:

    Command line:

    dotnet add package AspNetCore.AsyncInitialization

    Package manager console:

    Install-Package AspNetCore.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 Startup.ConfigureServices method:

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

About

Async initialization in ASP.NET Core 2.x

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •