.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 整合。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
  • 管理基礎的存留期 HttpClientMessageHandlerManages 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 用戶端, AddGrpcClient 可以在中使用泛型擴充方法 Startup.ConfigureServices ,並指定 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 建立 HttpClient gRPC 用戶端使用的。HttpClientFactory creates the HttpClient used by the gRPC client. 標準 HttpClientFactory 方法可以用來新增外寄要求中介軟體或設定的基礎 HttpClientHandler HttpClientStandard 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.
  • 新增 Interceptor 用戶端在進行 gRPC 呼叫時將使用的實例。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

gRPC 服務中的 factory 所建立的 gRPC 用戶端可以設定 EnableCallContextPropagation() 為,以自動將期限和取消權杖傳播至子呼叫。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. EnableCallContextPropagation()擴充方法可在Grpc. AspNetCore. ClientFactory NuGet 套件中取得。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();

根據預設, EnableCallContextPropagation 如果用戶端是在 gRPC 呼叫的內容之外使用,則會引發錯誤。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. 如果您想要在呼叫內容之外使用用戶端,請在設定用戶端時隱藏錯誤 SuppressContextNotFoundErrorsIf 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