When should I use IHostApplicationLifetime.OnStarted event vs IHostedService.StartAsync?
Asked Answered
A

0

7

I have been investigating the us of the .NET generic host for hosting console applications. It seems like the recommended pattern for .NET going forwards allowing for easy use of DI, logging, configuration, etc. while maintaining a consistent API as compared to ASP.NET web applications. I was starting to understand it somewhat when I ran across this example from Microsoft exemplifying the use of IHostApplicationLifetime events:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace AppLifetime.Example;

public class ExampleHostedService : IHostedService
{
    private readonly ILogger _logger;

    public ExampleHostedService(
        ILogger<ExampleHostedService> logger,
        IHostApplicationLifetime appLifetime)
    {
        _logger = logger;

        appLifetime.ApplicationStarted.Register(OnStarted);
        appLifetime.ApplicationStopping.Register(OnStopping);
        appLifetime.ApplicationStopped.Register(OnStopped);
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("1. StartAsync has been called.");

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("4. StopAsync has been called.");

        return Task.CompletedTask;
    }

    private void OnStarted()
    {
        _logger.LogInformation("2. OnStarted has been called.");
    }

    private void OnStopping()
    {
        _logger.LogInformation("3. OnStopping has been called.");
    }

    private void OnStopped()
    {
        _logger.LogInformation("5. OnStopped has been called.");
    }
}

I played around with this a bit and found that the boilerplate logging where .NET broadcasts that the application is starting always gets logged after my StartAsync method. This leads me to wonder: is there any general guidance of when and for what these two different patterns should be used for (IHostApplicationLifetime.OnStarted vs IHostedService.StartAsync)? It seems like implementing IHostedService is discussed more in the docs, but it seems strange to me that the StartAsync calls appear to happen before the host app lifetime is truly “started” - is there anything lost/to worry about due to that?

Avogadro answered 24/12, 2021 at 6:37 Comment(1)
One is starting, the other is started?Ineffable

© 2022 - 2024 — McMap. All rights reserved.