[英]access BackgroundService from controller in asp.net core 2.1
I just need to access my BackgroundService from a controller. 我只需要从控制器访问我的BackgroundService 。 Since BackgroundServices are injected with 因为BackgroundServices是注入的
services.AddSingleton<IHostedService, MyBackgroundService>()
How can I use it from a Controller class? 如何在Controller类中使用它?
最后,我在控制器中注入了IEnumerable<IHostedService>
,并按类型进行过滤: background.FirstOrDefault(w => w.GetType() == typeof(MyBackgroundService)
This is how I solved it: 这就是我解决它的方式:
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; }
}
Then in Startup
: 然后在Startup
:
services.AddTransient<IHostedServiceAccessor<MyBackgroundService>, HostedServiceAccessor<MyBackgroundService>>();
And in my class that needs access to the background service... 在我班上需要访问后台服务......
public class MyClass
{
private readonly MyBackgroundService _service;
public MyClass(IHostedServiceAccessor<MyBackgroundService> accessor)
{
_service = accessor.Service ?? throw new ArgumentNullException(nameof(accessor));
}
}
Add BackgroundService in ConfigureServices function: 在ConfigureServices函数中添加BackgroundService:
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<ListenerService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Inject in the Controller: 在控制器中注入:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IHostedService listenerService;
public ValuesController(IHostedService listenerService)
{
this.listenerService = listenerService;
}
}
I used BackgroundService to spin up multiple listeners for AWSSQS Listeners. 我使用BackgroundService来为AWSSQS Listener启动多个监听器。 If consumer wants to spin new listener then it could be done by POSTing to a Controller method (end point). 如果消费者想要旋转新的监听器,则可以通过POST到Controller方法(终点)来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.