我只需要从控制器访问我的BackgroundService 。由于 BackgroundServices 被注入
services.AddSingleton<IHostedService, MyBackgroundService>()
如何从 Controller 类中使用它?
我只需要从控制器访问我的BackgroundService 。由于 BackgroundServices 被注入
services.AddSingleton<IHostedService, MyBackgroundService>()
如何从 Controller 类中使用它?
最后我注入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>>();
在我需要访问后台服务的班级中......
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 到控制器方法(端点)来完成。