无法解析“ GraphQL.Http.IDocumentWriter”类型的服务

时间:2018-11-11 12:31:47

标签: asp.net-core-mvc graphql asp.net-core-webapi

在整个后续项目中,我只在项目中使用了仅跟随控制器。

https://github.com/graphql-dotnet/examples/blob/master/src/AspNetWebApi/Example/Controllers/GraphQLController.cs

此处的Controller文件如下。

using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using GraphQL.Http;
using GraphQL.Instrumentation;
using GraphQL.Types;
using GraphQL.Validation.Complexity;

namespace GraphQL.GraphiQL.Controllers
{
    public class GraphQLController : ApiController
    {
        private readonly ISchema _schema;
        private readonly IDocumentExecuter _executer;
        private readonly IDocumentWriter _writer;
        private readonly IDictionary<string, string> _namedQueries;

        public GraphQLController(
            IDocumentExecuter executer,
            IDocumentWriter writer,
            ISchema schema)
        {
            _executer = executer;
            _writer = writer;
            _schema = schema;

            _namedQueries = new Dictionary<string, string>
            {
                ["a-query"] = @"query foo { hero { name } }"
            };
        }

        // This will display an example error
        [HttpGet]
        public Task<HttpResponseMessage> GetAsync(HttpRequestMessage request)
        {
            return PostAsync(request, new GraphQLQuery { Query = "query foo { hero }", Variables = null });
        }

        [HttpPost]
        public async Task<HttpResponseMessage> PostAsync(HttpRequestMessage request, GraphQLQuery query)
        {
            var inputs = query.Variables.ToInputs();
            var queryToExecute = query.Query;

            if (!string.IsNullOrWhiteSpace(query.NamedQuery))
            {
                queryToExecute = _namedQueries[query.NamedQuery];
            }

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema = _schema;
                _.Query = queryToExecute;
                _.OperationName = query.OperationName;
                _.Inputs = inputs;

                _.ComplexityConfiguration = new ComplexityConfiguration { MaxDepth = 15 };
                _.FieldMiddleware.Use<InstrumentFieldsMiddleware>();

            }).ConfigureAwait(false);

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            var json = _writer.Write(result);

            var response = request.CreateResponse(httpResult);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return response;
        }
    }

    public class GraphQLQuery
    {
        public string OperationName { get; set; }
        public string NamedQuery { get; set; }
        public string Query { get; set; }
        public Newtonsoft.Json.Linq.JObject Variables { get; set; }
    }
}

当我尝试调用此控制器时,出现以下错误。

InvalidOperationException: Unable to resolve service for type 'GraphQL.Http.IDocumentWriter' while attempting to activate 'MyWebAppNamespace.Controllers.GraphQLController'.

我需要任何启动配置,还是可以使用此独立控制器?我想念什么?

1 个答案:

答案 0 :(得分:1)

  

我需要任何启动配置,还是可以使用此独立控制器?我想念什么?

正如错误所描述的,之所以发生,是因为DI容器无法解析IDocumentWriter的服务。

似乎您缺少一些服务注册。您是否忘了添加IDocumentWrite服务?

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));

    services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
    services.AddSingleton<IDocumentWriter, DocumentWriter>();

    // ...
    services.AddSingleton<ISchema, StarWarsSchema>();
    // ...
 }

有关更多详细信息,请参见startup here

  

还是我可以使用此独立控制器?

不。你不应该那样做。这是因为您的控制器依赖于IDocumentExecuterIDocumentWriterISchema服务。它们都通过依赖注入解决。在解析控制器之前,您必须注册所有服务。