3

配置服务

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”。

更多细节。

4

1 回答 1

2

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

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());
    }
}
于 2019-10-22T17:38:30.200 回答