我正在尝试利用 GraphQL.net 中的依赖注入来解析图形类型上的字段,但我不断收到以下错误:
System.Exception: Failed to call Activator.CreateInstance. Type: graphql_di.Models.MyObjectGraphType
---> System.MissingMethodException: Cannot dynamically create an instance of type 'graphql_di.Models.MyObjectGraphType'. Reason: No parameterless constructor defined.
我已经设置了一个干净的 .NET 6 Web API 来测试它,如下所示:
我的对象.cs
public class MyObject
{
public MyObject(string someProperty)
{
SomeProperty = someProperty;
}
public string SomeProperty { get; }
}
MyObjectGraphType
public class MyObjectGraphType : ObjectGraphType<MyObject>
{
public MyObjectGraphType(IMyService myService)
{
Field<StringGraphType>(name: "someProperty", resolve: x => x.Source?.SomeProperty ?? string.Empty);
Field<StringGraphType>(name: "name", resolve: x => myService.GetMyName());
}
}
RootQuery.cs
public class RootQuery : ObjectGraphType
{
public RootQuery()
{
Field<MyObjectGraphType>(
name: "myquery",
resolve: _ =>
{
MyObject myObject = new("some pre-populated property");
return myObject;
}
);
}
}
MySchema.cs
public class MySchema : Schema
{
public MySchema(IServiceProvider serviceProvider) : base(serviceProvider)
{
Query = serviceProvider.GetRequiredService<RootQuery>();
}
}
程序.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddMvc()
.AddMvcOptions(x => x.EnableEndpointRouting = false);
builder.Services.AddSingleton<IMyService, MyService>();
builder.Services.AddGraphQL()
.AddSchema<MySchema>()
.AddDataLoader()
.AddGraphTypes();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI();
app.Run();
依赖注入在某种意义上是有效的,我可以注入IMyService
到RootQuery
s constrcutor 中,但它不起作用MyObjectGraphType
有谁知道我在这里想念什么?
非常感谢任何帮助/提示:-)