-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Open
Labels
area-Extensions-HostingdocumentationDocumentation bug or enhancement, does not impact product or test codeDocumentation bug or enhancement, does not impact product or test codein-prThere is an active PR which will close this issue when it is mergedThere is an active PR which will close this issue when it is merged
Milestone
Description
Description
class FooService : IHostedService
{
public FooService() {}
/* ... */
}
class BarService : IHostedService
{
public BarService(FooService foo) {}
/* ... */
}
services.AddHostedService<FooService>(); // works
services.AddHostedService<BarService>(); // crashes when because DI container does not find FooServiceThe issue is quite straight forward in the .NET source code because the THostedService is not registered but instead a IHostedService ...
public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, THostedService>());
return services;
}The common workaround seems to be like
services.AddSingleton<FooService>();
services.AddSingleton<BarService>();
services.AddHostedService(sp => sp.GetService<FooService>());
services.AddHostedService(sp => sp.GetService<BarService>());My expectation was clearly, that the type I register with a ServiceCollection.Add* function later can be retrieved. I lost several hours due to this until I found the answer somewhere on StackOverflow.
Configuration
- .NET 5
- OS/Arch: Does not matter
Regression?
No
Other information
If the vote is not to double register the service (I assume the IHostedService is needed for the host logic), I would at least propose to add a warning in the documentation and maybe the function inline documentation.
jakmeier
Metadata
Metadata
Assignees
Labels
area-Extensions-HostingdocumentationDocumentation bug or enhancement, does not impact product or test codeDocumentation bug or enhancement, does not impact product or test codein-prThere is an active PR which will close this issue when it is mergedThere is an active PR which will close this issue when it is merged