Running ASP.NET Core 7.0. & GraphQL 7.6.1.
I'm trying to create a minimum viable example of schema first GraphQL with GraphQL.NET, but query is not resolving. The GraphQL resolves in the console, but not in the API, so likely a DI problem...
I keep getting a message
Error trying to resolve field 'user'
Schema
type Query {
user: User
}
type User {
id: String!
name: String!
}
User.cs
public class User
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
public class Query
{
[GraphQLMetadata("user")]
public User GetUser()
{
return new User { Id = "1", Name = "Simpleton" };
}
}
Program.cs
// Get the schema information
FileInfo fileInfo = new(Path.Join(AppContext.BaseDirectory, "schema.gql"));
var schemaText = await GetSchema(fileInfo);
var schema = Schema.For(schemaText,
sb =>
{
sb.Types.Include<Query>();
});
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGraphQL(b => b
.AddSchema(schema) // schema
.AddSystemTextJson()); // serializer
builder.Services.AddSingleton<IDataService, DataService>();
builder.Services.AddLogging(b => b.AddConsole());
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseGraphQLPlayground();
}
app.UseGraphQL("/graphql"); // url to host GraphQL endpoint
await app.RunAsync();
Simple fix, just needed to register the attributed Query class as a service:
builder.Services.AddSingleton<Query>();