Julius
Julius

Reputation: 745

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

I am experimenting with a gRPC service and client using proto files. The advice is to use gRPC client factory integration in .NET Core (https://learn.microsoft.com/en-us/aspnet/core/grpc/clientfactory?view=aspnetcore-3.1). To do this you register the client derived from Grpc.Core.ClientBase that is generated by the Grpc.Tools package, like this:

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

My understanding is that MyGrpcClientType is registered with DI as a transient client, meaning a new one is created each time it is injected, but that the client is integrated with the HttpClientFactory, allowing the channel to be reused rather than be created each time.

Now, I would like to use protobuf-net.grpc to generate the client from an interface, which appears to be done like this:

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

If I am correct in thinking that channels are expensive to create, but clients are cheap, how do I achieve integration with the HttpClientFactory (and so reuse of the underlying channel) using protobuf-net.grpc? The above appears to create a GrpcChannel each time I want a client, so what is the correct approach to reusing channels?

Similarly, is it possible to register the protobuf-net.grpc generated service class with the below code in ASP.Net Core?

endpoints.MapGrpcService<MyGrpcServiceType>();

(Please correct any misunderstandings in the above)

Upvotes: 2

Views: 4299

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062780

The Client Factory support not exists, and works exactly like documented here except you register with the method

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

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062780

Note that you don't need the AllowUnencryptedHttp2 - that's just if you aren't using https, but: you seem to be using https.

On the "similarly"; that should already work - the only bit you might be missing is the call to services.AddCodeFirstGrpc() (usually in Startup.cs, via ConfigureServices).

As for the AddGrpcClient; I would have to investigate. That isn't something that I've explored in the integrations so far. It might be a new piece is needed.

Upvotes: 2

Related Questions