Any good examples on usage of AutoRegisteringObjectGraphType with GraphQL.net

Viewed 206

Can anyone help me to get some sample code with examples regarding usage of AutoRegisteringObjectGraphType with asp.net core project? I did not find any concrete examples with documentation.

Any help on this is much appreciated.

1 Answers

Here is a sample of an auto registering input graph type:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Field<StringGraphType>("addPerson",
    arguments: new QueryArguments(
        new QueryArgument<AutoRegisteringInputObjectGraphType<Person>> { Name = "value" }
    ),
    resolve: context => {
        var person = context.GetArgument<Person>("value");
        db.Add(person);
        return "ok";
    });

Here is a sample of an auto registering object graph type that modifies some of the fields:

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime LastUpdated { get; set; }
}

class ProductGraphType : AutoRegisteringObjectGraphType<Product>
{
    public ProductGraphType()
        : base(x => x.LastUpdated)
    {
        GetField("Name").Description = "A short name of the product";
    }
}

Field<ListGraphType<ProductGraphType>>("products", resolve: _ => db.Products);

Note that you may need to register the classes within your dependency injection framework:

services.AddSingleton<EnumerationGraphType<Episodes>>();
services.AddSingleton<AutoRegisteringInputGraphType<Person>>();
services.AddSingleton<ProductGraphType>();

Alternatively, you can register open generic classes:

services.AddSingleton(typeof(AutoRegisteringInputGraphType<>));
services.AddSingleton(typeof(AutoRegisteringObjectGraphType<>));
services.AddSingleton(typeof(EnumerationGraphType<>));

In the above sample, you would still need to register ProductGraphType separately.

You can try exploring with the UTs here : https://github.com/graphql-dotnet/graphql-dotnet/blob/c3ca5d68a119c126e4bd64bc7ae9faade76e53c7/src/GraphQL.Tests/Types/ComplexGraphTypeTests.cs#L85

Example link in the docs : https://github.com/graphql-dotnet/graphql-dotnet/blob/master/docs2/site/docs/guides/known-issues.md

Related