繁体   English   中英

我可以对多个 GraphQL 模式使用依赖注入吗?

[英]Can I use dependency injection for multiple GraphQL Schemas?

我目前有两个可用的模式可以解析完全不同的查询。 此时 azure function 启动文件在进行依赖注入过程时只需要最近添加的模式。 所以查询只解析到最近添加的 Schema。 我相信这是与正在使用的界面的命名冲突,但我实际上不知道如何解决它。

我尝试将服务添加为瞬态和范围。

builder.Services.AddTransient<ISchema>(_ => new SchemaOne(new FuncDependencyResolver(type => (IGraphType)_.GetRequiredService(type))));
builder.Services.AddTransient<ISchema>(_ => new SchemaTwo(new FuncDependencyResolver(type => (IGraphType)_.GetRequiredService(type))));

或者

builder.Services.AddScoped<ISchema>(_ => new SchemaOne(new FuncDependencyResolver(type => (IGraphType)_.GetRequiredService(type))));
builder.Services.AddScoped<ISchema>(_ => new SchemaTwo(new FuncDependencyResolver(type => (IGraphType)_.GetRequiredService(type))));

目标是能够让两个查询解析到它们各自的模式。 此时{ queryOne { name } }返回错误"message": "Cannot query field \"queryOne\" on type \"QueryTwoType\".",

查看@user1672994 提供的链接后,我选择创建自己的接口,然后将其注入到 azure function 中。 我选择这样做的原因是因为我想为 azure function 提供选择使用的模式的机会。 我无法在提供的链接中找到该用例的解决方案。

Azure Function 依赖注入代码

builder.Services.AddTransient<ISchemaMapper>(_ => new SchemaMapper(new Dictionary<string,ISchema> {
{"SchemaOne", new SchemaOne(new FuncDependencyResolver(type => (IGraphType)_.GetRequiredService(type))) },
{"SchemaTwo", new SchemaTwo(new FuncDependencyResolver(type => (IGraphType)_.GetRequiredService(type))) } }));

使用的接口

public interface ISchemaMapper
{
  ISchema GetSchema(string schema);
}

接口的实现

public class SchemaMapper : ISchemaMapper
{
   public Dictionary<string, ISchema> mappedSchema;
   public SchemaMapper(Dictionary<string, ISchema> mappedSchemas)
   {
      this.mappedSchema = mappedSchemas;
   }

   public ISchema GetSchema(string schema)
   {
      return mappedSchema[schema];
   }
}

在这一点上,这是一种解决冲突依赖注入的 hacky 方法,但如果我找到更好的方法或者它在未来会变得强大,我会更新。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM