GraphQL DataLoader的空上下文

时间:2019-08-30 15:32:53

标签: c# asp.net-core graphql-dotnet

在我的使用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。为什么它为空?

2 个答案:

答案 0 :(得分:1)

如果您忘记执行查询之前添加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行。

答案 1 :(得分:-1)

还需要确保 services.AddMvc(); 在startup.ConfigureServices()

中的所有其他内容之前