.NET Core 中的 gRPC 客户端工厂集成gRPC client factory integration in .NET Core

gRPC 与 HttpClientFactory 的集成提供了一种创建 gRPC 客户端的集中方式。gRPC integration with HttpClientFactory offers a centralized way to create gRPC clients. 它可用作配置独立 gRPC 客户端实例的替代方法。It can be used as an alternative to configuring stand-alone gRPC client instances. Grpc.Net.ClientFactory NuGet 包中提供了工厂集成。Factory integration is available in the Grpc.Net.ClientFactory NuGet package.

工厂具有以下优势:The factory offers the following benefits:

  • 提供了用于配置逻辑 gRPC 客户端实例的中心位置Provides a central location for configuring logical gRPC client instances
  • 可管理基础 HttpClientMessageHandler 的生存期Manages the lifetime of the underlying HttpClientMessageHandler
  • 在 ASP.NET Core gRPC 服务中自动传播截止时间和取消Automatic propagation of deadline and cancellation in an ASP.NET Core gRPC service

注册 gRPC 客户端Register gRPC clients

若要注册 gRPC 客户端,可在 Startup.ConfigureServices 中使用通用的 AddGrpcClient 扩展方法,并指定 gRPC 类型化客户端类和服务地址:To register a gRPC client, the generic AddGrpcClient extension method can be used within Startup.ConfigureServices, specifying the gRPC typed client class and service address:

services.AddGrpcClient<Greeter.GreeterClient>(o =>
{
    o.Address = new Uri("https://localhost:5001");
});

gRPC 客户端类型通过依赖项注入 (DI) 注册为暂时性。The gRPC client type is registered as transient with dependency injection (DI). 现在可以在由 DI 创建的类型中直接注入和使用客户端。The client can now be injected and consumed directly in types created by DI. ASP.NET Core MVC 控制器、SignalR 中心和 gRPC 服务是可以自动注入 gRPC 客户端的位置:ASP.NET Core MVC controllers, SignalR hubs and gRPC services are places where gRPC clients can automatically be injected:

public class AggregatorService : Aggregator.AggregatorBase
{
    private readonly Greeter.GreeterClient _client;

    public AggregatorService(Greeter.GreeterClient client)
    {
        _client = client;
    }

    public override async Task SayHellos(HelloRequest request,
        IServerStreamWriter<HelloReply> responseStream, ServerCallContext context)
    {
        // Forward the call on to the greeter service
        using (var call = _client.SayHellos(request))
        {
            await foreach (var response in call.ResponseStream.ReadAllAsync())
            {
                await responseStream.WriteAsync(response);
            }
        }
    }
}

配置 HttpClientConfigure HttpClient

HttpClientFactory 创建 gRPC 客户端使用的 HttpClientHttpClientFactory creates the HttpClient used by the gRPC client. 标准 HttpClientFactory 方法可用于添加传出请求中间件或配置 HttpClient 的基础 HttpClientHandlerStandard HttpClientFactory methods can be used to add outgoing request middleware or to configure the underlying HttpClientHandler of the HttpClient:

services
    .AddGrpcClient<Greeter.GreeterClient>(o =>
    {
        o.Address = new Uri("https://localhost:5001");
    })
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        var handler = new HttpClientHandler();
        handler.ClientCertificates.Add(LoadCertificate());
        return handler;
    });

有关详细信息,请参阅使用 IHttpClientFactory 发出 HTTP 请求For more information, see Make HTTP requests using IHttpClientFactory.

配置通道和侦听器Configure Channel and Interceptors

特定于 gRPC 的方法可用于:gRPC-specific methods are available to:

  • 配置 gRPC 客户端的基础通道。Configure a gRPC client's underlying channel.
  • 添加客户端在进行 gRPC 调用时将使用的 Interceptor 实例。Add Interceptor instances that the client will use when making gRPC calls.
services
    .AddGrpcClient<Greeter.GreeterClient>(o =>
    {
        o.Address = new Uri("https://localhost:5001");
    })
    .AddInterceptor(() => new LoggingInterceptor())
    .ConfigureChannel(o =>
    {
        o.Credentials = new CustomCredentials();
    });

截止时间和取消传播Deadline and cancellation propagation

可以使用 EnableCallContextPropagation() 对 gRPC 服务中工厂所创建的 gRPC 客户端进行配置,以自动将截止时间和取消令牌传播到子调用。gRPC clients created by the factory in a gRPC service can be configured with EnableCallContextPropagation() to automatically propagate the deadline and cancellation token to child calls. Grpc.AspNetCore.Server.ClientFactory NuGet 包中提供了 EnableCallContextPropagation() 扩展方法。The EnableCallContextPropagation() extension method is available in the Grpc.AspNetCore.Server.ClientFactory NuGet package.

调用上下文传播的工作方式是:从当前 gRPC 请求上下文中读取截止时间和取消令牌,并自动将其传播到 gRPC 客户端所发出的传出调用。Call context propagation works by reading the deadline and cancellation token from the current gRPC request context and automatically propagating them to outgoing calls made by the gRPC client. 调用上下文传播是确保复杂的嵌套 gRPC 场景始终传播截止时间和取消的一种极佳方式。Call context propagation is an excellent way of ensuring that complex, nested gRPC scenarios always propagate the deadline and cancellation.

services
    .AddGrpcClient<Greeter.GreeterClient>(o =>
    {
        o.Address = new Uri("https://localhost:5001");
    })
    .EnableCallContextPropagation();

默认情况下,如果客户端在 gRPC 调用的上下文之外使用,EnableCallContextPropagation 将引发错误。By default, EnableCallContextPropagation raises an error if the client is used outside the context of a gRPC call. 此错误旨在提醒你没有要传播的调用上下文。The error is designed to alert you that there isn't a call context to propagate. 如果要在调用上下文之外使用客户端,请使用 SuppressContextNotFoundErrors 在配置客户端时禁止显示该错误:If you want to use the client outside of a call context, suppress the error when the client is configured with SuppressContextNotFoundErrors:

services
    .AddGrpcClient<Greeter.GreeterClient>(o =>
    {
        o.Address = new Uri("https://localhost:5001");
    })
    .EnableCallContextPropagation(o => o.SuppressContextNotFoundErrors = true);

有关截止时间和 RPC 取消的详细信息,请参阅 RPC 生命周期For more information about deadlines and RPC cancellation, see RPC life cycle.

其他资源Additional resources