简体   繁体   中英

.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));
}

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.

我通过在启动期间设置的类中静态存储引用来临时处理该问题。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM