SHARE:

gRPC & ASP.NET Core 3.1: How to create a gRPC client ?

Creating a gRPC client

In this example we will create a .NET Core 3.1 console application. Remember gRPC is designed for backend to backend communication with RPC commands.

We need to install a bunch of Nuget packages:

Install-Package Grpc.Tools 2.27.0
Install-Package Google.Protobuf 3.11.3
Install-Package Grpc.Net.ClientFactory 2.27.0
Install-Package Grpc.Net.Client 2.27.0
Install-Package Microsoft.Extensions.DependencyInjection 3.1.2

Then we import as the required .proto file in the .csproj as “Client” this time. The .csproj should like this:

If you compile you app, auto-generated classes should be well created (same process as server side service):

Now we can write our client in console app, using ServiceProvider and Grpc.Net.ClientFactory to be able to register easily our HttpClient with the extension method named AddGrpcClient. Once the client is created from ServiceProvider we can write our client methods.

Catching errors is quite simple, any error raised by the client is a RpcException. There is everything you need to debug your failing call.

Here is its signature:

NB: This a gRPC specificity, passing parameters is mandatory, even if a service method doesn’t need parameters, so the method named WhoIsAsync uses an empty object EmptyRequest.

Reminder of the .proto file used in this sample:

Demo

Here what we get after execution:

Conclusion

In this tutorial, we learned how to create a new gRPC client, we have also previously seen how does gRPC work and how do we create a server-side service. These three first articles were only required basics to understand gRPC in ASP.NET Core, in next articles we will go deeper with ASP.NET Core 3.1 & gRPC. The serious things will finally start 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.