Extensions.Hosting.AsyncInitialization Save Abandoned

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

Project README

Extensions.Hosting.AsyncInitialization

NuGet version AppVeyor build AppVeyor tests

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

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(CancellationToken cancellationToken)
        {
            // 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();
    }
    

    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.

Open Source Agenda is not affiliated with "Extensions.Hosting.AsyncInitialization" Project. README Source: thomaslevesque/Extensions.Hosting.AsyncInitialization
Stars
36
Open Issues
2
Last Commit
9 months ago
License

Open Source Agenda Badge

Open Source Agenda Rating