我只需要从控制器中访问我的BackgroundService。由于BackgroundServices是通过依赖注入来实现的,
services.AddSingleton<IHostedService, MyBackgroundService>()
我该如何在控制器类中使用它?
我只需要从控制器中访问我的BackgroundService。由于BackgroundServices是通过依赖注入来实现的,
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));
}
}
private readonly Guid _id = Guid.NewGuid();
并观察它在服务启动时与通过IHostedServiceAccessor获取时的值,您会发现它们是两个不同的值。 - UtopiaLtd 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;
}
}
public ControllerName(IHostedService service){ .. }
。在向此处提问之前,您是否尝试阅读文档?https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection - Roman MarusykStart()
的实例。 - Chris Marisic