1

在我使用graphql-dotnet的项目中,我意外地开始收到错误消息说 DataLoader 上下文为空:

Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.ArgumentNullException: Value cannot be null.
Parameter name: context
  at GraphQL.DataLoader.DataLoaderContextExtensions.GetOrAddBatchLoader[TKey,T](DataLoaderContext context, String loaderKey, Func`3 fetchFunc, IEqualityComparer`1 keyComparer, T defaultValue)

context参数来自IDataLoaderContextAccessor注入到图形类型的构造函数中的那个。为什么会为空?

4

2 回答 2

3

context如果您忘记DataLoaderDocumentListener在执行查询之前添加参数(就像我做的那样),该参数将为空:

public GraphQLController(
    ISchema schema,
    IDocumentExecuter documentExecuter,
    DataLoaderDocumentListener dataLoaderListener)
{
    _schema = schema;
    _documentExecuter = documentExecuter;
    _dataLoaderListener = dataLoaderListener;
}

[HttpPost]
public async Task<IActionResult> Post([FromBody]BaseGraphQuery query)
{
    var inputs = query.Variables.ToInputs();
    var executionOptions = new ExecutionOptions
    {
        Schema = _schema,
        Query = query.Query,
        Inputs = inputs,
    };

    // Important!
    executionOptions.Listeners.Add(_dataLoaderListener);

    // (Execute the query)
}

并且DataLoaderDocumentListener必须存在于服务容器中:

public void ConfigureServices(IServiceCollection services)
{
    // (other service configuration)

    services.AddSingleton<GraphQL.DataLoader.IDataLoaderContextAccessor, GraphQL.DataLoader.DataLoaderContextAccessor>();
    services.AddSingleton<GraphQL.DataLoader.DataLoaderDocumentListener>();
    services.AddSingleton<GraphQL.IDocumentExecuter, GraphQL.DocumentExecuter>();
    services.AddSingleton<GraphQL.Types.ISchema, RootSchema>();
}

准确但模糊的错误消息让我感到困惑,直到我想起我已经“重构”了一些代码并Listeners.Add错误地删除了该行。

于 2019-08-30T15:32:53.697 回答
-1

此外,您需要确保 services.AddMvc(); 在 startup.ConfigureServices() 中的所有其他内容之前

于 2020-03-25T13:20:49.163 回答