【问题标题】:How to access HotChocolate (GraphQL) requested query using IoC如何使用 IoC 访问 HotChocolate (GraphQL) 请求的查询
【发布时间】:2020-01-09 12:27:17
【问题描述】:

我正在尝试使用 hotchocolate 提高 sql 查询性能。为此,我想在我的应用程序的另一层访问由 hotchololate 生成的查询请求。我能找到的唯一方法是拦截请求,使用 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 entity-framework-core hotchocolate


    【解决方案1】:

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

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

    我的代码中的完整示例:

    public async Task<IEnumerable<Tenant>> GetTenants([Service]IHttpContextAccessor httpContext)
    {
        var tenantId = await httpContext.HttpContext.GetUserTenantId();
        return await _metadataRepo.Tenants.Get(x => x.TenantId == tenantId);
    }
    

    您不需要创建拦截器。 HttpContext 已经在 HotChocolate 的 DI 中了。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-26
      • 2021-07-09
      • 2022-09-25
      • 2021-08-27
      • 2022-10-19
      • 2018-03-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多