我只需要从控制器访问我的 backgroundService 即可。由于背景服务注入
services.AddSingleton<IHostedService, MyBackgroundService>()
如何从控制器类中使用它?
最后,我在控制器中注入了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));
}
}
在配置服务功能中添加背景服务:
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;
}
}
我使用背景服务来为AWSSQS听众旋转多个听众。如果消费者想旋转新侦听器,则可以通过发布到控制器方法(终点(来完成。