dapr / dotnet-sdk

Dapr SDK for .NET
Apache License 2.0
1.12k stars 340 forks source link

Include Samples for Grpc Proxy #828

Open Sen-Gupta opened 2 years ago

Sen-Gupta commented 2 years ago

Include Samples for Experimental Grpc Proxy

The sample contains examples of invoking grpc and uses InvokeGrpcAsync

Will it be possible to include sample based on Grpc Proxy as shown here.

https://docs.dapr.io/developing-applications/building-blocks/service-invocation/howto-invoke-services-grpc/

cwe1ss commented 2 years ago

I'd also like to know how to properly do this with dependency injection in ASP.NET Core.

I'm currently using the following code:

// invoker should be singleton according to docs
var otherServiceInvoker = DaprClient.CreateInvocationInvoker("other-service"); 

builder.Services.AddTransient(_ => new OtherService.ServiceClient(otherServiceInvoker));

I'm wondering though if I should/could use .AddGrpcClient() from Grpc.Net.ClientFactory? I somehow couldn't make it work with that yet.

RemcoBlok commented 1 year ago

I use DaprClient.CreateInvocationInvoker with protobuf-net.Grpc for a code-first approach.

I could not find a way to use the protobuf-net.Grpc.ClientFactory. The documentation of DaprClient.CreateInvocationInvoker suggests the returned CallInvoker can be registered as a singleton. And the protobuf-net.Grpc client instance is a thin veneer over the CallInvoker. See https://github.com/protobuf-net/protobuf-net.Grpc/issues/172. So I have

builder.Services.AddSingleton(_ => DaprClient.CreateInvocationInvoker("greeter-service").CreateGrpcService<IGreeterService>());
Flern commented 1 year ago

For anybody who'd like to see a working example (based on code in the above post), here's a quick way to add a client with the ASP.NET 6 DI container, assuming you have daprPort defined for the correct gRPC port and daprToken for token authentication. Not sure if this is the "right" or "best" way, but it works:

services.AddGrpcClient<OtherServiceClient>(
    options =>
    {
        options.Address = new Uri( $"http://localhost:{daprPort}" );
        options.Creator = _ => new OtherServiceClient( DaprClient.CreateInvocationInvoker( "other-service", null, daprToken ) );
    } );

Now... if anybody could show me how to set channel options on this, my day would be made!