43

I am trying to add a Background Timer in ASP.NET Core 3.0, which periodically executes a task. Google led me to this, where I implemented the 'Timed background tasks'. However, I'm stuck in resolving the HostedService in the controller. I need a specific instance of TimedHealthCheckService so I can call another public function called 'GetAvailableODataUrl()'.


In the startup.cs I use the following code:

services.AddHostedService<TimedHealthCheckService>();

The TimedHealthCheckService obviously implements IHostedService:

public class TimedHealthCheckService : IHostedService, IDisposable                  

In my controller, I have the following constructor:

public HealthCheckController(ILogger<HealthCheckController> logger, IHostedService hostedService)
{
  this.logger = logger;
  this.timedHealthCheckService = hostedService as TimedHealthCheckService;
}

However, when I start my WebAPI, the timedHealthCheckService is always null. It seems another IHostedService gets injected into the constructor. By checking hostedService, it is actually an object of type GenericWebHostService.

If I change the controller's constructor to:

public HealthCheckController(ILogger<HealthCheckController> logger, TimedHealthCheckService hostedService)

I am getting the following error:

Unable to resolve service for type 'HealthCheck.Web.TimedHealthCheckService' while attempting to activate 'HealthCheck.Web.Controllers.HealthCheckController'.

I also tried services.AddSingleton<IHostedService, TimedHealthCheckService>(); with the same result.

6
  • Why do you need to inject the hosted service? This might be an XY problem.
    – Nkosi
    Commented Oct 15, 2019 at 15:40
  • hosted services are automatically started by the framework so I am trying to understand why you need to get an instance of the service injected into the controller.
    – Nkosi
    Commented Oct 15, 2019 at 15:42
  • @Nkosi This hostedService will hold the actual health state. So I would like to get this state directly from the hostedService. Commented Oct 15, 2019 at 15:44
  • I suggest changing the design. Have an intermediate service that can be injected into both the controller and the hosted service. Make the service singleton so that state can be shared between them
    – Nkosi
    Commented Oct 15, 2019 at 16:06
  • @Nkosi I guess that's a viable option, thank you. However, I am still wondering why IHostedService cannot be injected as expected. Is it by design? Commented Oct 15, 2019 at 20:31

1 Answer 1

95

Try these two lines in startup.cs:

services.AddSingleton<TimedHealthCheckService>();
services.AddHostedService<TimedHealthCheckService>(provider => provider.GetService<TimedHealthCheckService>());

The first line above tells the service provider to create a singleton and give it to anyone who wants a TimedHealthCheckService, like your controller's constructor. However, the service provider is unaware that the singleton is actually an IHostedService and that you want it to call StartAsync().

The second line tells the service provider that you want to add a hosted service, so it'll call StartAsync() when the application starts running. AddHostedService accepts a Func<IServiceProvider,THostedService> callback. The callback we provide fetches the singleton TimedHealthCheckService from the service provider and returns it back to the service provider as an IHostedService. The service provider then calls its StartAsync() function.

And in your controller:

public HealthCheckController(ILogger<HealthCheckController> logger, TimedHealthCheckService hostedService)
5
  • Perfect, now it works, thank you. Can you elaborate on why a IServiceProvider is needed? Commented Oct 16, 2019 at 6:25
  • 3
    in asp.net core 2.1 AddHostedService doesn't accept arguments. any suggestions how to bypass this?
    – Nissim
    Commented Nov 13, 2019 at 14:58
  • The documentation claims that the overload of AddHostedService that takes a Func<> parameter is available in 2.1: learn.microsoft.com/en-us/dotnet/api/… Commented Nov 14, 2019 at 16:34
  • Hello @jeffrey Rennie, how to mock TimedHealthCheckService in XUNIT please? Commented Nov 17, 2021 at 15:39
  • 2
    Great! I also wonder why my class constructor is called twice even though I add it as "Singleton". So, the "Singleton" instance is used HostedSerivce unless I follow this answer.
    – F. Kam
    Commented Feb 17, 2023 at 1:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.