如何在 Hot Chocolate 中为查询类型拆分解析器

How to split resolvers for Query type in Hot Chocolate

我正在尝试实现标准的 GraphQL 实现,使用 .net 核心的 Hot Chocolate 库,其中读取数据的解析器属于根查询对象。 像这样:

{
  Query {
    GetTodo {
      Id
    }
  }
}

这是我尝试按照文档所做的,但它没有像我预期的那样工作:

startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ChocodotContext>();
            services.AddGraphQL(
                SchemaBuilder.New()
                .AddQueryType<QueryType>()
                .BindResolver<TodoQueries>()
                .Create()
            );
        }

Query.cs

using HotChocolate.Types;

namespace Queries
{
    public class QueryType : ObjectType
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            
        }
    }
}

TodoQueries.cs

using System.Threading.Tasks;
using HotChocolate;
using HotChocolate.Types;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Models;

namespace Queries
{
    [GraphQLResolverOf(typeof(Todo))]
    [GraphQLResolverOf("Query")]
    public class TodoQueries
    {
        public async Task<Todo> GetTodo([Service] ChocodotContext dbContext) {
            return await dbContext.Todos.FirstAsync();
        }        
    }

    public class TodoQueryType : ObjectType<TodoQueries> {
        
    }
}

我哪里不对?

你需要稍微改变一下:

query {
  todo {
    id
  }
}

startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ChocodotContext>();
    services.AddGraphQL(serviceProvider =>
        SchemaBuilder.New()
            .AddServices(serviceProvider)
            .AddQueryType<Query>()
            .AddType<TodoQueries>()
            .Create()
    );
}

Query.cs

using HotChocolate.Types;

namespace Queries
{
    public class Query
    {

    }
}

TodoQueries.cs

[ExtendObjectType(Name = "Query")]
public class TodoQueries
{
    // Side note, no need for async/await while it returns Task<>
    //
    public Task<Todo> GetTodo([Service] ChocodotContext dbContext) {
        return dbContext.Todos.FirstAsync();
    }        
}

使用 HotChocolate 10.5.2 测试

解决方案来源 - ChilliCream 博客,HotChocolate 10.3.0 文章,TypeAttributes 部分。