如何使用IoC访问热巧克力(GraphQL)请求的查询

如何使用IoC访问热巧克力(GraphQL)请求的查询,graphql,entity-framework-core,hotchocolate,Graphql,Entity Framework Core,Hotchocolate,我正在尝试使用热巧克力来提高sql查询性能。为此,我想在我的应用程序的另一层中访问由Hotcholote生成的queryrequest。我能找到的唯一方法是拦截请求,用HttpContext项存储我需要的信息,然后在我需要的地方注入IHttpContextAccessor services.AddQueryRequestInterceptor(GraphQLRequestInterceptor); ... private Task GraphQLRequestInterceptor(HttpCo

我正在尝试使用热巧克力来提高sql查询性能。为此,我想在我的应用程序的另一层中访问由Hotcholote生成的queryrequest。我能找到的唯一方法是拦截请求,用HttpContext项存储我需要的信息,然后在我需要的地方注入IHttpContextAccessor

services.AddQueryRequestInterceptor(GraphQLRequestInterceptor);
...
private Task GraphQLRequestInterceptor(HttpContext context, IQueryRequestBuilder requestBuilder, CancellationToken cancellationToken)
{
    IReadOnlyQueryRequest request = requestBuilder.Create();
    context.Items.Add("graph", request);
}
然后通过注入IHttpContextAccessor来恢复它

public ClientesQueries(Microsoft.AspNetCore.Http.IHttpContextAccessor contextAccessor)
{
   var queryRequest = contextAccessor.HttpContext.Items["graph"] as IReadOnlyQueryRequest;
}
有了这段代码,我可以创建一个表达式来查询我的数据库,只查询客户机请求的数据


有没有更好的方法来实现这一点?

我不确定我的答案是否是您请求的答案,但这就是我在graphql请求中访问httpContext的方式

只需添加:
[Service]IHttpContextAccessor httpContext
作为方法的第一个参数

我的代码中的完整示例:

公共异步任务GetTenants([Service]IHttpContextAccessor httpContext)
{
var tenantId=wait httpContext.httpContext.GetUserTenantId();
return wait\u metadataRepo.Tenants.Get(x=>x.TenantId==TenantId);
}
您不需要创建拦截器。HttpContext已经在热巧克力的DI中


祝你好运

我不确定我的答案是否是您请求的答案,但这就是我在graphql请求中访问httpContext的方式

只需添加:
[Service]IHttpContextAccessor httpContext
作为方法的第一个参数

我的代码中的完整示例:

公共异步任务GetTenants([Service]IHttpContextAccessor httpContext)
{
var tenantId=wait httpContext.httpContext.GetUserTenantId();
return wait\u metadataRepo.Tenants.Get(x=>x.TenantId==TenantId);
}
您不需要创建拦截器。HttpContext已经在热巧克力的DI中

祝你好运