GraphQL 服务的依赖注入

Dependency Injection of services for GraphQL

我正在使用带有 HotChocolate 包的 NET5 webapi 并尝试注入服务。 我遵循了标准和基于方法的方法 documented here 但是它根本不起作用。我得到的只是以下消息:

{
  "errors": [
    {
      "message": "Unexpected Execution Error",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "tests"
      ]
    }
  ],
  "data": {
    "tests": null
  }
}

我的查询:

query{
  tests {
    id
  }
}

我的代码目前反映了记录的方法方法。

启动中:

services
            .AddSingleton<ITestService, TestService>()
            .AddGraphQLServer()
            .AddDefaultTransactionScopeHandler()
            .AddQueryType<Queries>()
            .AddMutationType<Mutations>()
            .AddFiltering()
            .AddSorting()
            .AddProjections()
            .AddType<Test>();

查询设置:

        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<Test> GetTests([Service] ITestService testService) => testService.GetTests();

我的测试服务:

private readonly IDbContextFactory<TestDbContext> contextFactory;

public TestService(IDbContextFactory<TestDbContext> contextFactory)
{
    this.contextFactory = contextFactory;
}

public IQueryable<Test> GetTests()
{
    using var context = contextFactory.CreateDbContext();

    return context.Test;
}

我确定我缺少一些简单的东西来完成这项工作。

您的数据库上下文已处理。 GetTests 中的 using 适用于此方法。在此方法结束时,数据库上下文被释放并返回一个 Queryable。一旦执行引擎执行Queryable,就会抛出异常

查看 HotChocolate 的 EF Core 集成: https://chillicream.com/docs/hotchocolate/integrations/entity-framework