title: How to inject a reference to a specific IHostedService implementation?
body: <p>My web app has a background service that listens to a service bus. Based on the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1" rel="noreferrer">docs</a>, it looks like the built-in way to run a background service is to implement <code>IHostedService</code>.</p>
  
  <p>So I have some code that looks like this:</p>
  
  <pre><code>public class ServiceBusListener : IMessageSource&lt;string&gt;, IHostedService
  {
      public virtual event ServiceBusMessageHandler&lt;string&gt; OnMessage = delegate { };
  
      public Task StartAsync(CancellationToken cancellationToken)
      {
          // run the background task...
      }
  
      // ... other stuff ...
  }
  </code></pre>
  
  <p>The service is then registered in <code>Startup.cs</code> with:</p>
  
  <pre><code>services.AddSingleton&lt;IHostedService, ServiceBusListener&gt;();
  </code></pre>
  
  <p>Once I update to ASP.NET 2.1 I can use the new convenience method:</p>
  
  <pre><code>services.AddHostedService&lt;ServiceBusListener&gt;();
  </code></pre>
  
  <p>But I believe the two are functionally equivalent.</p>
  
  <p><strong>The complication:</strong> my web app has multiple implementations of <code>IHostedService</code> (specifically, different instances of service bus listeners).</p>
  
  <p><strong>The question:</strong> how can I have some other component get a reference to a specific hosted service implementation (my service bus listener)? In other words, how do I get a specific instance injected into a component?</p>
  
  <p><strong>Use case:</strong> my background service listens for service bus messages and then re-publishes messages as .NET events (in case you're wondering, the consuming code deals with the threading issues). If the event is on the background service, then subscribers need to get a reference to the background service to be able to subscribe.</p>
  
  <p><strong>What I've tried:</strong> if I do the obvious thing and declare <code>ServiceBusListener</code> as a dependency to be injected into a different component, my startup code throws a "Could not resolve a service of type" exception.</p>
  
  <p>Is it even possible to request a specific implementation of a <code>IHostedService</code>? If not, what's the best workaround? Introduce a third component that both my service and the consumer can reference? Avoid <code>IHostedService</code> and run the background service manually?</p>