Skip to content

Microsoft.Extensions.Hosting.Host creates hosted services too early. #14585

@dotnetjunkie

Description

@dotnetjunkie

Describe the bug

ASP.NET Core 3.0's new Microsoft.Extensions.Hosting.Host creates hosted services between Startup's ConfigureServices and Configure methods, where the 'old' Microsoft.AspNetCore.WebHost creates the hosted services only after the Configure method has run.

To Reproduce

  1. Create a vanilla ASP.NET Core (Model-View-Controller) Web Application project for ASP.NET Core 3.0.
  2. Create an empty MyHostedService class that implements IHostedService.
  3. Add the following registration to the Startup.ConfigureServices method: services.AddSingleton<IHostedService>(p => new MyHostedService());
  4. Run the application
  5. The p => new MyHostedService() is invoked after Startup.ConfigureServices ran, but before Startup.Configure runs.

Expected behavior

The delegate should run only after Startup.Configure ran.

Additional context

This behavior difference between Microsoft.AspNetCore.WebHost and Microsoft.Extensions.Hosting.Host is significant, because it disallows users of non-conforming containers (like Simple Injector, Castle Windsor, and Ninject) to resolve hosted services from their container, because the configuration of those containers needs to be finished in the Startup.Configure phase, while resolving hosted services from that container before that configuration is finished, can lead to problems. Simple Injector, for instance, blocks any registrations made after the first resolve (which will be a resolve for MyHostedService if you assume the hosted service to be added using p => container.GetInstance<MyHostedService>()). But even if the container doesn't block registrations, the early request for hosted services can cause trouble, because the hosted service's dependencies might not be registered at that point.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-hostingIncludes Hostingarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions