从ASP.NET Core 2.1中的控制器访问BackgroundService

Ale*_*oto 7 c# background-service asp.net-core asp.net-core-2.1

我只需要从控制器访问我的BackgroundService。由于BackgroundServices被注入

services.AddSingleton<IHostedService, MyBackgroundService>()
Run Code Online (Sandbox Code Playgroud)

如何从Controller类使用它?

Ale*_*oto 6

最后,我注入IEnumerable<IHostedService>了控制器并按类型过滤:background.FirstOrDefault(w => w.GetType() == typeof(MyBackgroundService)


Dou*_*son 4

这就是我解决它的方法:

public interface IHostedServiceAccessor<T> where T : IHostedService
{
  T Service { get; }
}

public class HostedServiceAccessor<T> : IHostedServiceAccessor<T>
  where T : IHostedService
{
  public HostedServiceAccessor(IEnumerable<IHostedService> hostedServices)
  {
    foreach (var service in hostedServices) {
      if (service is T match) {
        Service = match;
        break;
      }
    }
  }

  public T Service { get; }
}
Run Code Online (Sandbox Code Playgroud)

然后在Startup

services.AddTransient<IHostedServiceAccessor<MyBackgroundService>, HostedServiceAccessor<MyBackgroundService>>();
Run Code Online (Sandbox Code Playgroud)

在我的班级中,需要访问后台服务......

public class MyClass
{
  private readonly MyBackgroundService _service;

  public MyClass(IHostedServiceAccessor<MyBackgroundService> accessor)
  {
    _service = accessor.Service ?? throw new ArgumentNullException(nameof(accessor));
  }
}
Run Code Online (Sandbox Code Playgroud)