title: How to use a database context in a singleton service?
body: <p>I would like to store completed chess games in the database to support users watching replays.</p>
  
  <p>So far I have a singleton <code>GameManager</code> that stores all ongoing games. So within <code>startup.cs</code> I have the following line of code:</p>
  
  <pre><code>services.AddSingleton&lt;IBattleManager, BattleManager&gt;();
  </code></pre>
  
  <p>Now I would like to have <code>BattleManager</code> access the <code>DbContext</code> to save completed games.</p>
  
  <pre><code>public class BattleManager : IBattleManager
  {
      //...
      private void EndGame(ulong gameId)
      {
          var DbContext = WhatDoIPutHere?
          lock(gameDictionary[gameId])
          {
              DbContext.Replays.Add(new ReplayModel(gameDictionary[gameId]));
              gameDictionary.Remove(gameId)
          }
      }
  }
  </code></pre>
  
  <p>Is it possible to anyhow achieve this? How?</p>
  
  <p>Failed attempts:</p>
  
  <pre><code>public class BattleManager : IBattleManager
  {
      Data.ApplicationDbContext _context;
      public BattleManager(Data.ApplicationDbContext context)
      {
          _context = context;
      }
  }
  </code></pre>
  
  <p>This will clearly fail since one cannot inject EF Core <code>DbContext</code> into a Singleton service like that.</p>
  
  <p>I have a vague feeling that I should do something of this kind:</p>
  
  <pre><code>using (var scope = WhatDoIPutHere.CreateScope())
  {
      var DbContext = scope.ServiceProvider.GetRequiredService&lt;ApplicationDbContext&gt;();
      DbContext.Replays.Add(new ReplayModel(...));
  }
  </code></pre>
  
  <p>Is this the right direction?</p>