.NET GraphQL中FieldAsync方法的替代方案是什么?
解决GraphQL.NET 8.0.2中FieldAsync过时的异步查询实现方案
在GraphQL.NET 8.0.2版本中,FieldAsync方法已被标记为过时,官方推荐使用返回FieldBuilder的Field方法或直接调用AddField方法来实现异步查询。针对你的场景,有两种可行的替代方案:
方案一:使用Field方法链式配置异步Resolver
通过Field方法获取FieldBuilder,再调用ResolveAsync方法传入异步逻辑,这是最简洁的写法:
public class ExampleQuery : ObjectGraphType { private readonly IExampleService _exampleService; public ExampleQuery(IExampleService exampleService) { _exampleService = exampleService; Field<ListGraphType<ExampleType>>("Examples") .ResolveAsync(async context => { return await _exampleService.GetExamples(); }); } }
方案二:直接使用AddField方法创建字段
手动构建FieldDefinition对象,指定字段名称、类型和异步Resolver,这种方式更灵活,适合需要自定义更多字段属性的场景:
public class ExampleQuery : ObjectGraphType { private readonly IExampleService _exampleService; public ExampleQuery(IExampleService exampleService) { _exampleService = exampleService; AddField(new FieldDefinition { Name = "Examples", Type = typeof(ListGraphType<ExampleType>), Resolver = new AsyncFieldResolver<object, List<Example>>(async context => { return await _exampleService.GetExamples(); }) }); } }
以上两种方式均符合GraphQL.NET 8.x的官方规范,能够完全替代原有的FieldAsync实现,同时消除CS0618和GQL004警告。
内容的提问来源于stack exchange,提问作者dede
相关产品推荐
相关产品推荐

