Reputation:
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.
Upvotes: 2
Views: 1669
Reputation: 6060
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.
You can use partial classes, but you might have to do some reflection magic to distribute the Code from the ctor. One could use reflection to call any method in the class that starts with "Init" for example. Then the partial classes can declare init methods and to what they need
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.
Upvotes: 2