使用适用于 .NET 和 EF Core 3.0 的 GraphQL 进行并行异步查询

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

总结

我目前正在将一个项目迁移到 AspNetCore 3.0,并且 运行 在一个查询中查询多个内容时遇到 GraphQL for .NET ParallelExecutionStrategy 的问题。该项目使用 MSSQL Server 作为数据存储,可通过 Entity Framework Core 3.0 访问。我得到的错误是:

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.

如果我实施 IDocumentExecuter 并更改 ParallelExecutionStrategy 以等待每个单独的执行,从 Task.WhenAllawait ExecuteNodeAsynchttps://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL/Execution/ParallelExecutionStrategy.cs#L27).

我正在尝试执行的示例查询:

query {
  thingA {
    id
  }
  thingB {
    id
  }
}

编辑:

使用 DbContextPool 似乎也没有解决问题:

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

我们正在使用 StructureMap 进行依赖注入,它为每个 HttpRequest 创建一个新的 DbContext,但我们需要为每个查询创建一个唯一的 DbContext,解决方案是创建一个嵌套容器并通过嵌套容器请求依赖项。

public Constructor(IContainer container) => _dbContext = container.GetNestedContainer()
    .GetInstance<DbContext>();

如果您正在使用内置的依赖注入容器,您应该考虑使用 IServiceScopeFactory<T>。它与 Ganhammar 基于 "StructureMap" 的答案本质上是相同的方法,只是它不是 "Service Locator"。 (相对简单的)IServiceScopeFactory<T>代码是here and another answer related to this question is here.

查看我解决此问题的实现。 “技巧”是在解析器级别创建范围 https://github.com/fenomeno83/graphql-dotnet-globalization-demo