如何在 graphql-dotnet 中注入数据库上下文

how to inject a database context in graphql-dotnet

配置服务

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: Cannot resolve scoped service 'Models.Database.Context' from root provider.

更多细节。

如果

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());
    }
}