title: Common DB Access repository for ASP.NET Core Web App and Worker Service - managing context
body: <p>I have an app with a common database requirement for an ASP.Net Core web app and an ASP.Net Core Worker service background task. I have a standard Repository pattern based approach with a class for each entity (standard CRUD operations).</p>
  <p>My question concerns the best approach to manage the Db context injection into the Repository class for both apps. This is easy for the ASP.Net Core web app: Constructor based DI each time a Db context is required. However, the worker service requires obtaining a fresh Db context for every ExecuteAsync iteration, and passing it to each repository class by some means. This works, but is a bit messy:</p>
  <p><code>code</code></p>
  <pre><code>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
          while (!stoppingToken.IsCancellationRequested)
          {
              using var scope = _serviceScopeFactory.CreateScope();
  
              var dbContext = scope.ServiceProvider.GetRequiredService&lt;MyDbContext&gt;();
              
              ...
          }
      }
  </code></pre>
  <p><code>code</code></p>
  <p>I'm interested in a single Db data access point design pattern that will manage both apps while also getting thread-safe Db contexts when required.</p>
  <p>Any help greatly appreciated</p>