asp.net-coreef-core-3.0graphql-dotnet

Parallel async queries with GraphQL for .NET and EF Core 3.0


Summary

I am currently migrating a project to AspNetCore 3.0 and are running into a issue with the GraphQL for .NET ParallelExecutionStrategy when querying for multiple things in one query. The project is using a MSSQL Server as the data store and it is access through Entity Framework Core 3.0. The error I get is:

A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.

I can resolve the issue if I implement IDocumentExecuter and change the ParallelExecutionStrategy to await each individual execution, from Task.WhenAll to await ExecuteNodeAsync (https://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL/Execution/ParallelExecutionStrategy.cs#L27).

Example query that I'm trying to execute:

query {
  thingA {
    id
  }
  thingB {
    id
  }
}

Edit:

Using DbContextPool doesn't seem to solve the problem either:

services.AddDbContextPool<DBCONTEXT>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("CONNECTIONSTRING")));

Solution

  • If you are using the built-in dependency injection container, you should consider using an IServiceScopeFactory<T>. It's essentially the same approach as Ganhammar's "StructureMap" based answer, except it's not a "Service Locator". The (relatively simple) IServiceScopeFactory<T> code is here and another answer related to this question is here.