Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access BackgroundService from controller in asp.net core 2.1

I just need to access my BackgroundService from a controller. Since BackgroundServices are injected with

services.AddSingleton<IHostedService, MyBackgroundService>()

How can I use it from a Controller class?

like image 748
Alex Troto Avatar asked Mar 28 '18 13:03

Alex Troto


2 Answers

In the end I've injected IEnumerable<IHostedService> in the controller and filtered by Type:background.FirstOrDefault(w => w.GetType() == typeof(MyBackgroundService)

like image 161
Alex Troto Avatar answered Sep 25 '22 12:09

Alex Troto


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:

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));
  }
}
like image 35
Doug Wilson Avatar answered Sep 21 '22 12:09

Doug Wilson