如何在 GraphQL-dotNet 中注入数据库上下文



ConfigureServices

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想要利用使用默认添加为作用域的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());
}
}

最新更新