![](/img/trans.png)
[英]How to run BackgroundService on a timer in ASP.NET Core 2.1
[英]access BackgroundService from controller in asp.net core 2.1
我只需要從控制器訪問我的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 Listener啟動多個監聽器。 如果消費者想要旋轉新的監聽器,則可以通過POST到Controller方法(終點)來完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.