0

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 RootQuerys constrcutor, but it's not working on MyObjectGraphType

Does anyone know what I am missing here?

Any help/hint is greatly appreciated :-)

bomortensen
  • 3,346
  • 10
  • 53
  • 74
  • The DI container cannot resolve the Fields defined in the the MyObjectGraphType. Try first removing those field and compile your code. Add a parameterless constructor to MyObjectGraphType. – maxspan Dec 16 '21 at 11:59
  • Thanks for your reply, @maxspan appreciated :-) I can see that the DI can't resolve the dependency, but.. if I need to resolve data for the `name` field on `MyObjectGraphType` from an external API, how exactly does one do that if the service cannot be injected? – bomortensen Dec 16 '21 at 12:21

0 Answers0