title: What is the best practice in EF Core for using parallel async calls with an Injected DbContext?
body: <p>I have a .NET Core 1.1 API with EF Core 1.1 and using Microsoft's vanilla setup of using Dependency Injection to provide the DbContext to my services. (Reference: <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro#register-the-context-with-dependency-injection" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro#register-the-context-with-dependency-injection</a>)</p>
  
  <p>Now, I am looking into parallelizing database reads as an optimization using <a href="https://msdn.microsoft.com/en-us/library/hh194766(v=vs.110).aspx" rel="noreferrer">WhenAll</a> </p>
  
  <p>So instead of:</p>
  
  <pre><code>var result1 = await _dbContext.TableModel1.FirstOrDefaultAsync(x =&gt; x.SomeId == AnId);
  var result2 = await _dbContext.TableModel2.FirstOrDefaultAsync(x =&gt; x.SomeOtherProp == AProp); 
  </code></pre>
  
  <p>I use:</p>
  
  <pre><code>var repositoryTask1 = _dbContext.TableModel1.FirstOrDefaultAsync(x =&gt; x.SomeId == AnId);     
  var repositoryTask2 = _dbContext.TableModel2.FirstOrDefaultAsync(x =&gt; x.SomeOtherProp == AProp);   
  (var result1, var result2) = await (repositoryTask1, repositoryTask2 ).WhenAll();
  </code></pre>
  
  <p>This is all well and good, until I use the same strategy outside of these DB Repository access classes and call these same methods with WhenAll in my controller across multiple services:</p>
  
  <pre><code>var serviceTask1 = _service1.GetSomethingsFromDb(Id);
  var serviceTask2 = _service2.GetSomeMoreThingsFromDb(Id);
  (var dataForController1, var dataForController2) = await (serviceTask1, serviceTask2).WhenAll();
  </code></pre>
  
  <p>Now when I call this from my controller, randomly I will get concurrency errors like: </p>
  
  <blockquote>
    <p>System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.</p>
  </blockquote>
  
  <p>The reason I believe is because sometimes these threads try to access the same tables at the same time. <a href="https://docs.microsoft.com/en-us/ef/core/querying/async" rel="noreferrer">I know that this is by design in EF Core</a> and if I wanted to I could create a new dbContext every time, but I am trying to see if there is a workaround. That's when I found this good post by Mehdi El Gueddari: <a href="http://mehdi.me/ambient-dbcontext-in-ef6/" rel="noreferrer">http://mehdi.me/ambient-dbcontext-in-ef6/</a></p>
  
  <p>In which he acknowledges this limitation:  </p>
  
  <blockquote>
    <p>an injected DbContext prevents you from being able to introduce multi-threading or any sort of parallel execution flows in your services.</p>
  </blockquote>
  
  <p>And offers a custom workaround with <code>DbContextScope</code>.</p>
  
  <p>However, he presents a caveat even with DbContextScope in that it won't work in parallel (what I'm trying to do above):</p>
  
  <blockquote>
    <p>if you attempt to start multiple parallel tasks within the context of
    a DbContextScope (e.g. by creating multiple threads or multiple TPL
    Task), you will get into big trouble. This is because the ambient
    DbContextScope will flow through all the threads your parallel tasks
    are using.</p>
  </blockquote>
  
  <p>His final point here leads me to my question:</p>
  
  <blockquote>
    <p>In general, parallelizing database access within a single business transaction has little to no benefits and only adds significant complexity. Any parallel operation performed within the context of a business transaction should not access the database.</p>
  </blockquote>
  
  <p>Should I not be using WhenAll in this case in my Controllers and stick with using await one-by-one? Or is dependency-injection of the DbContext the more fundamental problem here, therefore a new one should instead be created/supplied every time by some kind of factory?</p>