Skip to content

Minimal API does not start HostedService before accepting requests #35454

@koenbeuk

Description

@koenbeuk

According to these docs:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio

StartAsync(CancellationToken): StartAsync contains the logic to start the background task. StartAsync is called before:
- The app's request processing pipeline is configured (Startup.Configure).
- The server is started and IApplicationLifetime.ApplicationStarted is triggered.

This seems no longer the case for minimal api's. Consider the following example:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<SomeBackgroundService>();

var app = builder.Build(); 
app.MapGet("/", (SomeBackgroundService s) => s.State);
app.Run(); 

class SomeBackgroundService : IHostedService  {
    public int State= 0;
    public async Task StartAsync(CancellationToken _) {
        State = 1;
        await Task.Delay(5000);
        State = 2;
    }
}

Running this app will immediately start accepting requests. The first request (assuming you're quick enough) will return 0. Subsequent requests will return 1 before finally returning 2 (Started).

I would expect IHostedService to work the same with minimal api's as it does with the generic host. Or is this by design?

Further technical details

dotnet  --info
.NET SDK (reflecting any global.json):
 Version:   6.0.100-preview.7.21379.14
 Commit:    22d70b47bc

Metadata

Metadata

Assignees

Labels

Priority:0Work that we can't release withoutarea-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-minimal-hostingold-area-web-frameworks-do-not-use*DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions