从 asp.net 核心 2.1 中的控制器访问 BackgroundService

access BackgroundService from controller in asp.net core 2.1

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

services.AddSingleton<IHostedService, MyBackgroundService>()

如何从控制器使用它class?

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

我是这样解决的:

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

然后在 Startup:

services.AddTransient<IHostedServiceAccessor<MyBackgroundService>, HostedServiceAccessor<MyBackgroundService>>();

在我的 class 中需要访问后台服务...

public class MyClass
{
  private readonly MyBackgroundService _service;

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

在 ConfigureServices 函数中添加 BackgroundService:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHostedService<ListenerService>();


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

在控制器中注入:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IHostedService listenerService;

    public ValuesController(IHostedService listenerService)
    {
        this.listenerService = listenerService;
    }
}

我使用 BackgroundService 为 AWSSQS 侦听器启动多个侦听器。如果消费者想要旋转新的侦听器,则可以通过 POST 到控制器方法(终点)来完成。