配置服务
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.
更多细节。
最佳答案
如果
Query
和 Schema
想要利用默认添加为作用域的 DbContext
,则它也应该作用域。
services.AddDbContext<Context>(options => options.UseSqlServer(configuration.GetConnectionString("Default")));
services.AddScoped<Query>();
services.AddScoped<Schema>();
services.AddGraphQL()
.AddGraphTypes(ServiceLifetime.Scoped);;
Context
应该显式注入(inject)
public class Query : ObjectGraphType {
public Query(Context db) {
Name = "query";
Field<ListGraphType<Types.Note>>("notes", resolve: _ => db.Notes.AsAsyncEnumerable());
}
}
关于c# - 如何在 graphql-dotnet 中注入(inject)数据库上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509238/