简体   繁体   English

GraphQL dotnet core 查询 class 依赖注入

[英]GraphQL dotnet core Query class dependency injection

Update: Previous null error was because an empty constructor of Query class with no parameters is created.更新:以前的 null 错误是因为创建了没有参数的Query class 的空构造函数。 Now I removed that empty constructor, but get a new Error: System.MissingMethodException: No parameterless constructor defined for type 'App.Controllers.Graphs.Query'现在我删除了那个空的构造函数,但是得到了一个新的错误: System.MissingMethodException: No parameterless constructor defined for type 'App.Controllers.Graphs.Query'


How can you inject your service into the GraphQL Query class?如何将服务注入 GraphQL 查询 class? (Schema-first approach) (模式优先方法)

In my dotnet core 3.1 project, I have installed: GraphQL.Server.Transports.AspNetCore 3.5.0-alpha0046在我的 dotnet core 3.1 项目中,我安装了: GraphQL.Server.Transports.AspNetCore 3.5.0-alpha0046

Here is my root graph:这是我的根图:

  public class RootGraph : Schema
  {
    public RootGraph(IServiceProvider provider) : base(provider)
    {
      var schema = For(@"
        type Player {
          _id: ID!
          dbname: String!
          isPremium: Boolean!
          games: [String]!
        }

        input PlayerView {
          dbname: String!
          isPremium: Boolean!
        }

        type Query {
          player(dbname: String!): Player
        }
      ", _ =>
      {
        _.Types.Include<Query>();
      });

      Console.WriteLine(provider); // <-- provider is not null here, everything is good

      Query = schema.Query;
    }
  }

Then I create my Query class like this:然后我像这样创建我的查询 class :

  public class Query
  {
    private readonly ServiceProvider serviceProvider;
    private readonly IPlayerService playerService; 

    public Query( IServiceProvider serviceProvider )
    {
      this.serviceProvider = serviceProvider as ServiceProvider;
      this.playerService = serviceProvider.GetService<IPlayerService>();
    }

    [GraphQLMetadata("player")]
    public async Task<Player> GetPlayer(string dbname)
    {
      Console.WriteLine(serviceProvider);
      Player player = await playerService.Get(dbname);
      return player;
    }
  }

But it's not working.但它不起作用。 The Query class cannot be created, because I get an exception here:无法创建查询 class,因为我在这里遇到异常:

System.MissingMethodException: No parameterless constructor defined for type 'App.Controllers.Graphs.Query'.\r\n
at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)\r\n
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)\r\n
at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)\r\n 
at System.Activator.CreateInstance(Type type)\r\n  
at GraphQL.DefaultServiceProvider.GetService(Type serviceType)\r\n

Part of my Startup.cs :我的Startup.cs的一部分:

public void ConfigureServices(IServiceCollection services){

  ...

  // add services
  services.AddSingleton<IPlayerService, PlayerService>();

  // add GraphQL
  services.AddSingleton<RootGraph>();
  services.AddSingleton<Query>();
}

Anyone has an idea on how to provide services to Query class?任何人都知道如何为查询 class 提供服务?

You have towrite this code in the startup class.您必须在启动 class 中编写此代码。

services.AddScoped<IServiceProvider , ServiceProvider >();

and declare the interface type in the class and pass to constructor.并在 class 中声明接口类型并传递给构造函数。

private readonly IServiceProvider _serviceProvider ;

You can use AddSingleton , AddTransient or AddScoped as per the requirement您可以根据要求使用AddSingletonAddTransientAddScoped

So according to this thread , all I need to do is specify the service provider in the schema configuration, like this:所以根据这个线程,我需要做的就是在模式配置中指定服务提供者,如下所示:

    public RootGraph(IServiceProvider provider) : base(provider)
    {
      var schema = For(@"...", _ =>
      {
        _.Types.Include<Query>();
        _.ServiceProvider = provider; // <=== Add this line here

      });

      // ...

    }

You should be able to inject it directly without having to use the IServiceProvider.您应该能够直接注入它而无需使用 IServiceProvider。 Something like this:像这样的东西:

[GraphQLMetadata("Query")] 
public class Query
  {
    private readonly IPlayerService playerService; 

    public Query(IPlayerService playerService)
    {
      this.playerService = playerService;
    }

    [GraphQLMetadata("player")]
    public async Task<Player> GetPlayer(string dbname)
    {
      Console.WriteLine(serviceProvider);
      Player player = await playerService.Get(dbname);
      return player;
    }
  }

And then in your SchemaFile you have to add the ServiceProvider to your schema.然后在您的 SchemaFile 中,您必须将 ServiceProvider 添加到您的架构中。

  public class RootGraph : Schema
  {
    public RootGraph(IServiceProvider provider) 
        : base(provider)
    {
      var schema = For(@"
        ...
      ", _ =>
      {
        _.Types.Include<Query>();
        _.ServiceProvider = provider;
      });
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 ASP.NET Core 中实现 GraphQL(用于 .Net 的 GraphQL),为什么我的 Query:ObjectGraphType 类没有被依赖注入注册? - Implementing GraphQL (GraphQL for .Net) in ASP.NET Core, why is my Query:ObjectGraphType class not being registered by dependency injection? DotNet 核心依赖注入工厂类型 - DotNet Core Dependency Injection Factory Types 依赖注入到 SignalR 集线器(dotnet core 3.1) - Dependency Injection into SignalR Hub (dotnet core 3.1) 使用StructureMap.DependencyInjection在C#dotnet core 2.0中进行简单的代理类依赖注入 - Simple proxy class dependency injection in C# dotnet core 2.0 using StructureMap.DependencyInjection 使用dotnet核心2.1的AWS Lambda函数中的依赖注入 - Dependency Injection in AWS Lambda function using dotnet core 2.1 do.net core 获取依赖注入的已加载程序集列表 - dotnet core get a list of loaded assemblies for dependency injection 在调用 BuildServiceProvider 之前将 dotnet 核心依赖注入到扩展方法 - dotnet core dependency injection to extension method before BuildServiceProvider is called 自定义 Class - .NET 核心中的依赖注入 - Dependency Injection in Custom Class - .NET Core .NET Core 6 依赖注入:Class 与用户 - .NET Core 6 Dependency Injection: Class with User .NET Core 和抽象(基)类的依赖注入 - Dependency injection with .NET Core and abstract (base) class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM