Reputation: 3396
I'm trying to utilize dependency injection in GraphQL.net to resolve fields on a graph type, but I keep getting the following error:
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.
I've set up a clean .NET 6 web API for testing it, like so:
MyObject.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>();
}
}
Program.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();
Dependency injection is working in the sense, that I can inject IMyService
into RootQuery
s constrcutor, but it's not working on MyObjectGraphType
Does anyone know what I am missing here?
Any help/hint is greatly appreciated :-)
Upvotes: 0
Views: 672