title: How to start an ASP.NET Core BackgroundService on demand?
body: <p>I want to be able to start fire-and-forget jobs in ASP.NET Core 2.2. I have tried the following:</p>
  <pre><code>services.AddHostedService&lt;TestHostedService&gt;();
  
  
  public class TestHostedService : BackgroundService
  {
      private readonly ILogger _logger;
  
      public TestHostedService(ILoggerFactory loggerFactory)
      {
          _logger = loggerFactory.CreateLogger&lt;TestHostedService&gt;();
      }
  
      public IBackgroundTaskQueue TaskQueue { get; }
  
      protected async override Task ExecuteAsync(
          CancellationToken cancellationToken)
      {
          _logger.LogInformation(&quot;TestHostedService is starting.&quot;);
  
          _logger.LogInformation(&quot;TestHostedService is stopping.&quot;);
      }
  }
  </code></pre>
  <p>However, this automatically starts and I want to be able to start it on demand, similarly to how Hangfire allows:</p>
  <pre><code>BackgroundJob.Enqueue&lt;TestJob&gt;(x =&gt; x.DoWork());
  </code></pre>
  <p>This also allows the job to naturally use ASP.NET CORE DI.</p>
  <p><strong>Question:</strong> How to start an ASP.NET Core BackgroundService on demand?</p>
  <hr>
  <p>###Background information</p>
  <p>I am dealing with an application that needs to fire-and-forget various methods. The already written code looks like this:</p>
  <pre><code> Task.Run(() =&gt; RunSomething(_serviceScopeFactory));
  </code></pre>
  <p>This means that each method must explicitly deal with getting a scope and retrieving the dependencies which is quite ugly.</p>