title: GraphQL dotnet - Add fields at runtime using reflection
body: <p>We have a decent sized dataset that we are using graphql dotnet to query. We have custom logic in place to parse the GQL query string and generate a function that will select the appropriate fields from the database and not the full object.</p>
  <p>As such, the 'Query' object in our schema has a load of almost identical calls to <code>Field</code> in it which just look an object up by it's Id, issue the parsed select command, and return the resulting object.</p>
  <p>For example:</p>
  <pre><code>// expression based department query
  Field&lt;DepartmentType&gt;(
      &quot;department&quot;,
      arguments: new QueryArguments(
          new QueryArgument&lt;NonNullGraphType&lt;IdGraphType&gt;&gt; { Name = &quot;organisationId&quot; },
          new QueryArgument&lt;NonNullGraphType&lt;IdGraphType&gt;&gt; { Name = &quot;employerId&quot; },
          new QueryArgument&lt;NonNullGraphType&lt;IdGraphType&gt;&gt; { Name = &quot;Id&quot; }),
      resolve: context =&gt;
      {
          var query = context.Document.OriginalQuery.Substring(context.Document.OriginalQuery.IndexOf(&quot;{&quot;));
  
          var organisationId = new Guid(context.GetArgument&lt;string&gt;(&quot;organisationId&quot;));
          var employerId = new Guid(context.GetArgument&lt;string&gt;(&quot;employerId&quot;));
          var Id = new Guid(context.GetArgument&lt;string&gt;(&quot;Id&quot;));
  
          appContext.OrganisationId = organisationId;
          appContext.EmployerId = employerId;
  
          var retVal = database.Departments()
              .Where(x =&gt; x.Id == Id &amp;&amp; x.Deleted != true);
  
          var selectStatement = GraphDocumentParser.GenerateSelect(query, &quot;department&quot;);
          var builder = new ExpressionBuilder();
          var statement = builder.BuildSelector&lt;Department, Department&gt;(selectStatement);
          var result = retVal.Select(statement);
  
          return result.FirstOrDefault();
      }).AuthorizeWith(Constants.GraphQL.Policies.API_ACCESS);
  </code></pre>
  <p>So I thought that I could just use reflection to loop our graphql types like this:</p>
  <pre><code>var queryableObjectTypes = Assembly.GetExecutingAssembly().GetTypes()
      .Where(x =&gt; x.IsClass &amp;&amp; x.Namespace == &quot;my.namespace.query.api&quot; &amp;&amp; !x.FullName.Contains(&quot;+&lt;&gt;c&quot;))
      .ToList();
  
  //Loop through our GQL types
  foreach (var queryableObjectType in queryableObjectTypes)
  {
      Console.WriteLine(queryableObjectType.FullName);
  
      //Grab the fields property from the type
      var fieldsProperty = queryableObjectType.GetProperties().FirstOrDefault(x =&gt; x.Name == &quot;Fields&quot;);
  
      //If this has our 'fields' property which we require
      if (fieldsProperty != null)
      {
          //Get the instance of this
          var instanceOfType = database.GetServiceProvider().GetService(queryableObjectType);
  
          //If this fields is the type we definitely want - i.e.actually get the value from the
          // instance and check it
              if (fieldsProperty.GetValue(instanceOfType) is GraphQL.Types.TypeFields typeFields)
          {
              //If this type contains an employerid, then we need to generate a query for this
              if (typeFields.Any(x =&gt; x.Name.ToLower() == &quot;employerid&quot;))
              { ... } //These are the objects that I want to generate fields for
  </code></pre>
  <p>Which does give me the correct collection of GQL Type objects that I can loop over and use to add a field (any one of our objects with an employerId... which I will blacklist a few of later on, but that would be a simple list to skip over)</p>
  <p>I can then parse various bits like the 'base' entity that this type points to, and get most of the required data for the Field to add to our GQL query.</p>
  <p>I am able to get almost everything I need to create a field type to add to our query... as shown here:</p>
  <pre><code>var f = new FieldType();
  f.Name = genericTypeNameFormatted;
  f.Description = string.Empty;
  f.Type = queryableObjectType;
  f.Resolver = ????????
  f.Arguments = new QueryArguments(
      new QueryArgument&lt;NonNullGraphType&lt;IdGraphType&gt;&gt; { Name = &quot;organisationId&quot; },
      new QueryArgument&lt;NonNullGraphType&lt;IdGraphType&gt;&gt; { Name = &quot;employerId&quot; },
      new QueryArgument&lt;NonNullGraphType&lt;IdGraphType&gt;&gt; { Name = &quot;Id&quot; });
  f.AuthorizeWith(Constants.GraphQL.Policies.API_ACCESS);
  </code></pre>
  <p>However, I am totally stuck with the mix of generics etc.. required to create the resolver. It's definition is as follows:</p>
  <pre><code>public class AsyncFieldResolver&lt;TSourceType, TReturnType&gt; : IFieldResolver&lt;Task&lt;TReturnType&gt;&gt;
  {
      private readonly Func&lt;IResolveFieldContext&lt;TSourceType&gt;, Task&lt;TReturnType&gt;&gt; _resolver;
  
      /// &lt;inheritdoc cref=&quot;AsyncFieldResolver{TReturnType}.AsyncFieldResolver(Func{IResolveFieldContext, Task{TReturnType}})&quot;/&gt;
      public AsyncFieldResolver(Func&lt;IResolveFieldContext&lt;TSourceType&gt;, Task&lt;TReturnType&gt;&gt; resolver)
      {
          _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver), &quot;A resolver function must be specified&quot;);
      }
  
      /// &lt;inheritdoc cref=&quot;AsyncFieldResolver{TReturnType}.Resolve(IResolveFieldContext)&quot;/&gt;
      public Task&lt;TReturnType&gt; Resolve(IResolveFieldContext context) =&gt; _resolver(context.As&lt;TSourceType&gt;());
  
      object IFieldResolver.Resolve(IResolveFieldContext context) =&gt; Resolve(context);
  }
  </code></pre>
  <p>Is it possible to create a <code>Func&lt;IResolveFieldContext&lt;TSource&gt;, Task&lt;TReturn&gt;&gt;</code> using data from reflection etc? or is it actually not possible?</p>