How to configure a single gRpc channel when using multiple clients with AddCodeFirstGrpcClient

824 Views Asked by At

From what I understand, it's best to reuse gRPC channels. What is the right way to create multiple code-first clients which share address and handler configurations?

I have multiple ASP.NET gRPC services hosted at the same server/address. I want multiple clients to be configured in the same way and use to the single common channel. For example, I want to configure a GrpcWebHandler and a DelegatingHandler so I can use SetBrowserRequestCredentials. For context, I'm creating these clients in Blazor WebAssembly.

I'm also using the code-first approach with protobuf-net.grpc. But, all the documented examples I could find of ...Services.AddCodeFirstGrpcClient() seem to provide an Address with each client. I assume this results in a separate channel created for each client.

Here is an example repo which I'd like to update with the correct approach. https://github.com/vyrotek/blazor-wasm-codefirst-grpc/blob/main/Example/Client/Program.cs

1

There are 1 best solutions below

0
On

From what I could find, this seems to be the next best option.

This approach drops protobuf-net.Grpc.ClientFactory and instead creates the services manually.

var baseAddress = new Uri(builder.HostEnvironment.BaseAddress);

builder.Services.AddSingleton(services =>
{
    var httpHandler = new CredentialHandler(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
    return GrpcChannel.ForAddress(baseAddress, new GrpcChannelOptions { HttpHandler = httpHandler });
});

builder.Services.AddScoped(services =>
{
    return services.GetRequiredService<GrpcChannel>().CreateGrpcService<IAuthService>();
});

builder.Services.AddScoped(services =>
{
    return services.GetRequiredService<GrpcChannel>().CreateGrpcService<IWeatherForecastService>();
});