【问题标题】:GraphQL Parallel async queries c# EF Core 3.0GraphQL 并行异步查询 c# EF Core 3.0
【发布时间】:2023-03-19 17:39:02
【问题描述】:

我正在尝试使用 2 个(或更多)异步子查询执行查询。遗憾的是这是不可能的,因为DbContext 当时只能处理 1 个请求。

项目正在使用:

  • 实体框架 3
  • Graphql 3.0.0

错误

在前一个操作完成之前,在此上下文中启动了第二个操作。这通常是由使用相同 DbContext 实例的不同线程引起的。

类型:

Field<ListGraphType<A>>()
    .Name("A")
    .Description("query of A")
    .ResolveAsync(async context =>
        await repro.GetAllAAsync(context)
);

Field<ListGraphType<A>>()
            .Name("B")
            .Description("query of B")
            .ResolveAsync(async context =>
                await repro.GetAllBAsync(context)
            );

查询:

query {
  A {
    id
  }
  B {
    id
  }
}

DbContextPool 没有解决问题,我不想使用 StructureMap。

有没有优雅的使用方式

  • 每个子查询有多个 dbContext
  • 等到 dbContext 空闲

【问题讨论】:

    标签: c# entity-framework async-await graphql .net-core-3.0


    【解决方案1】:

    我最近创建了一个解决 EF 并行执行的项目。 你可以在这里看到实现

    https://github.com/fenomeno83/graphql-dotnet-globalization-demo

    特别是,这里有一个您可以找到的查询示例:

    public class TestGroupQueries : ObjectGraphType
    {
        public TestGroupQueries(IHttpContextAccessor _httpContextAccessor)
        {
            Name = "testQueries";
    
            FieldAsync<TestResponseType>(
                "demoQuery",
                    arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IntGraphType>> { Name = "input" }),
                    resolve: async context =>
                    {
                        //extension method that creates scope (IServiceScope) from IServiceProvider
                        using (var scope = _httpContextAccessor.CreateScope())
                        {
                           
                            //call DemoQuery method of TestService; GetService is an extension method that use GetRequiredService from scope serviceprovider
                            return await scope.GetService<ITestService>().DemoQuery(context.GetArgument<int>("input"));
                        }
                    });
    
           
        }
    

    您在解析器中创建一个新范围并使用此范围的服务

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2020-03-29
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多