title: EF core DbContext in a multithreaded API application
body: <blockquote>
  <p><strong>tl;dr</strong> How can I use Entity Framework in a multithreaded .NET Core API application even though DbContext is not threadsafe?</p>
  </blockquote>
  <h3>Context</h3>
  <p>I am working on a .NET Core API app exposing several RESTful interfaces that access the database and read data from it, while at the same time running several TimedHostedServices as background working threads that poll data regularly from other webservices and store them into the database.</p>
  <p>I am aware of the fact that DbContext is not threadsafe. I read a lot of docs, blog Posts and answers here on Stackoverflow, and I could find a lot of (partly contradictory) answers for this but no real &quot;best practice&quot; when also working with DI.</p>
  <h3>Things I tried</h3>
  <p>Using the default <code>ServiceLifetime.Scoped</code> via the <code>AddDbContext</code> extension method results in exceptions due to race conditions.</p>
  <p>I don't want to work with locks (e.g. Semaphore), as the obvious downsides are:</p>
  <ul>
  <li>the code is polluted with locks and try/catch/finally for safely releasing the locks</li>
  <li>it doesn't really seem 'robust', i.e. when I forget to lock a region that accesses the DbContext.</li>
  <li>it seems redundant and 'unnatural' to artificially syncronize db access in the app when working with a database that also handles concurrent connections and access</li>
  </ul>
  <p>Not injecting <code>MyDbContext</code> but <code>DbContextOptions&lt;MyDbContext&gt;</code> instead, building the context only when I need to access the db, using a <code>using</code> statement to immediatelly dispose it after the read/write seems like a lot of resource usage overhead and unnecessarily many connection opening/closings.</p>
  <h3>Question</h3>
  <p>I am really puzzled: how can this be achived?</p>
  <p>I don't think my usecase is super special - populating the db from a Background worker and querying it from the web API layer - so there should be a meaningful way of doing this with ef core.</p>
  <p>Thanks a lot!</p>