-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
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
- Create a vanilla ASP.NET Core (Model-View-Controller) Web Application project for ASP.NET Core 3.0.
- Create an empty
MyHostedServiceclass that implementsIHostedService. - Add the following registration to the
Startup.ConfigureServicesmethod:services.AddSingleton<IHostedService>(p => new MyHostedService()); - Run the application
- The
p => new MyHostedService()is invoked afterStartup.ConfigureServicesran, but beforeStartup.Configureruns.
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.