【问题标题】:how to inject a database context in graphql-dotnet如何在 graphql-dotnet 中注入数据库上下文
【发布时间】:2019-10-23 01:43:35
【问题描述】:

配置服务

services.AddSingleton<IServiceProvider>(c => new FuncServiceProvider(type => c.GetRequiredService(type)));
services.AddDbContext<Context>(options => options.UseSqlServer(configuration.GetConnectionString("Default")));

services.AddSingleton<Query>();
services.AddSingleton<Schema>();

services.AddGraphQL();

配置

app.UseGraphQL<Schema>();

查询

    public class Query : ObjectGraphType
    {
        public Query(IServiceProvider resolver)
        {
            var db = resolver.GetRequiredService<Context>();

            Name = "query";
            Field<ListGraphType<Types.Note>>("notes", resolve: _ => db.Notes.AsAsyncEnumerable());
        }
    }

执行 GraphQL 端点会导致以下异常

System.InvalidOperationException:无法从根提供程序解析范围服务“Models.Database.Context”。

更多细节。

【问题讨论】:

  • 为什么QuerySchema 是单身人士?
  • 我是从link推导出来的。 AddScoped 有效,但它的性能不是更差吗?
  • 该示例使用单例,因为它被用于中间件,基本上是单例。

标签: c# dependency-injection graphql-dotnet


【解决方案1】:

QuerySchema 如果想利用默认添加为作用域的DbContext,也应该使用作用域。

services.AddDbContext<Context>(options => options.UseSqlServer(configuration.GetConnectionString("Default")));

services.AddScoped<Query>();
services.AddScoped<Schema>();

services.AddGraphQL()
    .AddGraphTypes(ServiceLifetime.Scoped);;

Context 应该被显式注入

public class Query : ObjectGraphType {
    public Query(Context db) {
        Name = "query";
        Field<ListGraphType<Types.Note>>("notes", resolve: _ => db.Notes.AsAsyncEnumerable());
    }
}

【讨论】:

  • 您不妨考虑thisthis。如果您在多个字段中使用相同的 db,您将得到一个异常,因为解析器是并行执行的,而 EFC 的 DbContext 不执行多线程查询。
猜你喜欢
  • 2018-08-31
  • 1970-01-01
  • 2018-06-07
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 2022-07-31
  • 2022-10-05
相关资源
最近更新 更多