protobuf-net.grpc 客户端与.NET Core 的 gRPC 客户端工厂集成

protobuf-net.grpc client and .NET Core's gRPC client factory integration

我正在使用 proto 文件试验 gRPC 服务和客户端。建议是在 .NET Core 中使用 gRPC 客户端工厂集成 (https://docs.microsoft.com/en-us/aspnet/core/grpc/clientfactory?view=aspnetcore-3.1)。为此,您注册由 Grpc.Tools 包生成的 Grpc.Core.ClientBase 派生的客户端,如下所示:

Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services.AddGrpcClient<MyGrpcClientType>(o =>
        {
            o.Address = new Uri("https://localhost:5001");
        });
    })

我的理解是 MyGrpcClientType 是作为临时客户端注册到 DI 的,这意味着每次注入时都会创建一个新客户端,但是客户端与 HttpClientFactory 集成在一起,允许重用通道而不是每次创建。

现在,我想使用 protobuf-net.grpc 从接口生成客户端,这似乎是这样完成的:

GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress("http://localhost:10042");
var calculator = http.CreateGrpcService<ICalculator>();

如果我认为通道的创建成本很高,但客户端很便宜,那么我如何使用 protobuf-net.grpc 实现与 HttpClientFactory 的集成(以及底层通道的重用)?上面似乎每次我想要一个客户端时都会创建一个 GrpcChannel,那么重用通道的正确方法是什么?

同样,是否可以在 ASP.Net Core 中使用以下代码注册 protobuf-net.grpc 生成的服务 class?

endpoints.MapGrpcService<MyGrpcServiceType>();

(以上有误请指正)

请注意,您 不需要 AllowUnencryptedHttp2 - 如果您没有使用 https,那只是,但是:您似乎正在使用 https。

上"similarly";那应该已经可以工作了-您可能唯一缺少的是对 services.AddCodeFirstGrpc() 的调用(通常在 Startup.cs 中,通过 ConfigureServices)。

至于AddGrpcClient;我将不得不进行调查。到目前为止,这不是我在集成中探索的内容。可能需要新的一块。

Client Factory support not exists, and works exactly like documented here除了你注册的方法

services.AddCodeFirstGrpcClient<IMyService>(o =>
{
    o.Address = new Uri("...etc...");
});