首页 > 解决方案 > GraphQL 服务的依赖注入

问题描述

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

{
  "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;
}

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

标签: c#.nethotchocolate

解决方案


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

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


推荐阅读