Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to create a GraphQL API with .NET Core using the GraphQL and GraphiQL package. I created one query for users and one for tasks

public sealed class UserQuery : ObjectGraphType
{
    private List<User> users = new List<User>();

    public UserQuery()
    {
        Field<ListGraphType<UserType>>(
            "users",
            "Returns a collection of users.",
            resolve: context => users);
    }
}

public sealed class TaskQuery : ObjectGraphType
{
    private List<Task> tasks = new List<Task>();

    public TaskQuery()
    {
        Field<ListGraphType<TaskType>>(
            "tasks",
            "Returns a collection of tasks.",
            resolve: context => tasks);
    }
}

I created two schemas to "register" the queries

public sealed class UserSchema : GraphQL.Types.Schema
{
    public UserSchema(UserQuery userQuery)
    {
        Query = userQuery;
    }
}

public sealed class TaskSchema : GraphQL.Types.Schema
{
    public TaskSchema(TaskQuery taskQuery)
    {
        Query = taskQuery;
    }
}

Unfortunately I've seen that this is not possible because I have to register ISchema as a singleton service

serviceCollection
    .AddSingleton<ISchema, UserSchema>()
    .AddSingleton<ISchema, TaskSchema>();

So the TaskSchema overwrites the UserSchema. One solution would be to have one single schema with one single query containing the content of UserQuery and TaskQuery but things get messy really fast, no?

Any better ideas to split the resources?

I think things might get very complex when dealing with 100 fields or even more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

Every GraphQL schema needs to contain exactly one query type: https://graphql.org/learn/schema/

And one endpoint can only surface one schema. If you want to split it up into multiple files, you could use partial classes.

Alternatively, you could also explore hot chocolate, there you do not need to declare a single schema. You can add all the different query types and they are merged automatically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...