Jaroslav Langer
Jaroslav Langer

Reputation: 131

.NET Core Hosted Service

I need to get a reference of registred hosted service:

services.AddHostedService<DataCollectingService>();

It implements interface IHostedService and it properly starts at web application start.

I need to get the ref of the service in some controller and access object public members.

The following code doesn't work. xService is null.

public IActionResult T()
{
    using (var serviceScope = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        var xService = serviceScope.ServiceProvider.GetService<DataCollectingService>();

    }
    return RedirectToAction(nameof(Index));
}

Upvotes: 0

Views: 684

Answers (3)

Hursev
Hursev

Reputation: 51

The answer that works in .Net Core 3.1+ was given by gunr2171 in the 3rd comment of the original question:

IEnumerable<IHostedService> allHostedServices = this.serviceProvider.GetService<IEnumerable<IHostedService>>();

Will return references to the existing instances of the Hosted Services.

Upvotes: 1

rekiem87
rekiem87

Reputation: 1573

I would move all the functionality to a Singleton, then in my startup I would do something like

services.AddSingleton<DataCollectingService>();
services.AddHostedService<HostedServiceUsingTheDataCollectionService>();

Then I could inject the Singleton in the controllers.

I am not sure if Core will handle the same reference (I think in core 3 will be the case, not so sure for <=2.2), but I would give a try.

Upvotes: 0

Jaroslav Langer
Jaroslav Langer

Reputation: 131

I have temporaly handled that by storing reference staticly in class which is set durring start.

Upvotes: 0

Related Questions