title: ASP.NET Core AddHostedService and AddSingleton relationship
body: <p>I was using AddSingleton and AddHostedService together to have a long running service (BackgroundService) in the backend while controllers accessing the same service to fetch data.
  Here are what I found:</p>
  <ol>
  <li>If both AddSingleton and AddHostedService were used, the BackgroundService would be initialized twice (not Singleton).  The controller could only access the one created in AddSingleton.</li>
  </ol>
  <p>debug output (constructor called twice, see the difference in the seconds)</p>
  <blockquote>
  <p><strong>BGService constructor</strong> service addGame:games count is 1
  <strong>BGService constructor</strong> service addGame:games count is 1
  ExecuteAsync 1 :games
  count is 1:[   &quot;CONSTRUCTOR GAME AT 10/29/2021 10:37:25 AM(0)&quot; ]
  ......
  ExecuteAsync 7 :games count is 1:[   &quot;CONSTRUCTOR GAME AT 10/29/2021
  10:37:25 AM(0)&quot; ]
  service addGame:games count is 2 After AddGame: [<br />
  &quot;CONSTRUCTOR GAME AT 10/29/2021 10:37:24 AM(0)&quot;,   &quot;GAME 0(1)&quot; ]</p>
  </blockquote>
  <ol start="2">
  <li><p>If only AddSingleton was used, it worked.</p>
  </li>
  <li><p>If only AddHostedService was used, the BackgroundService was running, but DI not working in controller (Exception).</p>
  </li>
  </ol>
  <p>**&gt; fail:</p>
  <blockquote>
  <p>Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware<a href="https://github.com/huangpat/CoreServiceSignalRSample" rel="nofollow noreferrer">1</a>
  An unhandled exception has occurred while executing the request. System.InvalidOperationException: Unable to resolve service for type
  'CoreServiceSignalRSample.service.IBGService' while attempting to
  activate
  'CoreServiceSignalRSample.Controllers.WeatherForecastController'.<br />
  at
  Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
  sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)<br />
  at lambda_method(Closure , IServiceProvider , Object[] )**</p>
  </blockquote>
  <p>My question is, <strong>what is the proper way to DI a BackgroundService and why AddHostedService is recommended</strong>?</p>
  <p>The sample code can be found at <a href="https://github.com/huangpat/CoreServiceSignalRSample" rel="nofollow noreferrer">https://github.com/huangpat/CoreServiceSignalRSample</a>.</p>
  <p>Startup.cs ConfigureServices</p>
  <pre><code>    services.AddSingleton&lt;IBGService&gt;(new BGService());
      services.AddHostedService&lt;BGService&gt;();
  </code></pre>
  <p>BGSercie.cs</p>
  <pre><code>private List&lt;string&gt; games;
  
  public BGService()
  {
      Console.WriteLine(&quot;BGService constructor&quot;);
      this.games = new List&lt;string&gt;();
      this.addGame(&quot;Constructor Game at &quot; + DateTime.Now.ToString());
  }
  
  public async Task&lt;bool&gt; addGame(string fGame)
  {
      if (this.games.Count &lt;= 20)
      {
          this.games.Add(fGame.ToUpper() + &quot;(&quot; + Convert.ToString(this.games.Count) + &quot;)&quot;);
          Console.WriteLine(&quot;service addGame:games count is &quot; + Convert.ToString(this.games.Count));
          return true;
      }
      else
      {
          return false;
      }
  }
  
  
  protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  {
      int i = 0;
      while (true)
      {
          i++;
          if (games.Count == 0)
          {
              this.addGame(&quot;ExecuteAsync Game at &quot; + DateTime.Now.ToString());
          }
          JsonSerializer js = new JsonSerializer();
          
          Console.WriteLine(&quot;ExecuteAsync {1} :games count is {0}:{2}&quot;, this.games.Count, i, JsonConvert.SerializeObject(this.games, Formatting.Indented));
  
          await Task.Delay(1000 * 2 * 5);
      }
      //throw new NotImplementedException();
  
      /
  </code></pre>
  <p>/ use thread pool to start each game in collection
  }</p>