Skip to content

HostingAbstractionsHostExtensions RunAsync disposes without logging #72225

@snakefoot

Description

@snakefoot

Description

The RunAsync in HostingAbstractionsHostExtensions.cs disposes the Host on exit:

public static async Task RunAsync(this IHost host, CancellationToken token = default)
{
try
{
await host.StartAsync(token).ConfigureAwait(false);
await host.WaitForShutdownAsync(token).ConfigureAwait(false);
}
finally
{
if (host is IAsyncDisposable asyncDisposable)

This disposes the ServiceProvider and the LoggerFactory, so unable to perform any logging after this point.

Inside the Host StartAsync then it nicely logs Starting, but any exception happing in the following code is not caught and logged:

public async Task StartAsync(CancellationToken cancellationToken = default)
{
_logger.Starting();
using var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping);
CancellationToken combinedCancellationToken = combinedCancellationTokenSource.Token;
await _hostLifetime.WaitForStartAsync(combinedCancellationToken).ConfigureAwait(false);
combinedCancellationToken.ThrowIfCancellationRequested();
_hostedServices = Services.GetRequiredService<IEnumerable<IHostedService>>();

And because of the dispose, then any logging is impossible on exception:

Reproduction Steps

        var builder = Host.CreateDefaultBuilder();
        builder.ConfigureServices(s => s.AddHostedService<BrokenHostedService>());
        builder.Build().Run();

        class BrokenHostedService : IHostedService
        {
            public Task StartAsync(CancellationToken cancellationToken)
            {
                throw new Exception("Hosted service startup error!");
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                return Task.CompletedTask;
            }
        }

Expected behavior

Exception is logged to the Microsoft Console Provider.

Actual behavior

Application crashes without any trace.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions