Skip to content

AddHostedService does not register specified Type Parameter in DI container #53831

@tthiery

Description

@tthiery

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 FooService

The 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.

Metadata

Metadata

Assignees

Labels

area-Extensions-HostingdocumentationDocumentation bug or enhancement, does not impact product or test codein-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions