Introduction
In this post, we will learn how to create gRPC client applications. The gRPC server application has been explained in this
post.
About gRPC Client
gRPC client applications are used to communicate with gRPC server applications. Unlike SOAP or REST based services, we can’t consume or test a gRPC server application.
gRPC supports the below .NET Client Applications.
- ASP.NET Core, Win forms, WPF, Console application.
Create gRPC Client Library
If we are not sure about our type of client application, it's better to start with a common client library. We can reference this library to any client applications.
We need to below pre-requisites to create the library:
- Visual studio 2019
- .NET Core 3 or above
Step 1
First, create a .NET Core Class library:
Step 2
We need to install below Nuget Libraries for gRPC client application.
Libraries
- Google.Protobuf
- Grpc.Net.ClientFactory
- Grpc.Tools
Step 3
Create a Proto folder and add the below “Employee.proto” file. It’s the same proto file which we used in the gRPC server application.
All the method signatures need to be the same with the server application proto file.
In the below “Employee.proto” file, we have added the below elements:
- Included “EmployeeService” as "Service" that's mandatory for gRPC communication.
- Added two protocol buffer messages, "EmplyeeModel", "ResponseMessage" which is a small logical record of information, containing a series of name-value pairs.
- syntax = "proto3";
- import "google/protobuf/empty.proto";
- import "google/protobuf/Timestamp.proto";
-
- option csharp_namespace = "TestService.Protos";
-
- service EmployeeService{
- rpc GetAllEmployee(google.protobuf.Empty) returns (ResponseMessage);
- }
-
- message EmployeeModel{
- google.protobuf.Timestamp dateTimeStamp = 1;
- string name=2;
- string skill=3;
- string email=4;
- }
-
- message ResponseMessage{
- string message=1;
- bool success=2;
- repeated EmployeeModel employees=3;
- }
Step 4
We need to change the properties of the “.proto” files. We can update “Build Action” and “gRPC Stub Classes” properties as shown below.
Step 5
Once we build the application, we can verify the auto-generated files “Employee.cs” and “EmployeeGrpc.cs” in “obj/Debug” folder.
Step 6
Create a console application and add our “TestClient.GRPC.ClientLib” library project to the consoles' applications:
Step 7
We need to write the below code to connect gPRC server application. “EmployeeServiceClient” is available in an auto-generated code file “EmployeeGrpc.cs” which we saw in Step:5.
- namespace TestConsoleClient
- {
- class Program
- {
- static void Main(string[] args)
- {
- using var channel = GrpcChannel.ForAddress("https://localhost:5001");
-
- var client = new EmployeeServiceClient(channel);
-
- var reply = client.GetAllEmployee(new Empty());
-
- Console.WriteLine($"Result: {reply}");
-
- Console.WriteLine("Press a key to exit");
- Console.ReadKey();
- }
- }
- }
Step 8
Before we test our gRPC console application, make sure we ran the gRPC server application.
The server application has been started and running. We can notice the endpoint “http://localhost:5000” that we already used in “Step:7”.
After running our console application, we can see the results in console.
Step 9
Next, we will create a worker service client in our .NET Core application.
About WorkerService
Worker service can be implemented as hosted services which will run as background tasks. A hosted service is a class with background task logic that implements the IHostedService interface.
Select the worker service template project in Visual Studio and create the project.
Step 10
After creating the “TestWorkServiceClient” project, add a reference to the “TestClient.GRPC.ClientLib” library project.
Step 11
In Appsettings.json files add the below configuration. We will use the below configuration in the next step.
- "gRPCService": {
- "ServiceUrl": "https://localhost:5001"
- }
Step 11
Create a worker service class while will inherit from “BackgroundService” base class. Implement “ExecuteAsync” method to access our “GetAllEmployee” gRPC client method.
“BackgroundService” base class has few other virtual methods like “StartAsync”, “StopAsync” and we can override and use these methods if we host our worker service as windows background service.
Add a client property to read the service URL from the “AppSettings.json” file and instantiate “EmployeeServiceClient” object through gRPC client.
- protected EmployeeServiceClient Client
- {
- get
- {
- if (_client == null)
- {
- var channel = GrpcChannel.ForAddress(_config["gRPCService:ServiceUrl"]);
- _client = new EmployeeServiceClient(channel);
- }
- return _client;
- }
- }
“ExecuteAsync” method has the below code to access the gRPC method:
- var result = Client.GetAllEmployee(new Empty());
Below, the worker service code has been added for your reference:
- public class Worker : BackgroundService
- {
- private readonly ILogger<Worker> _logger;
- private readonly IConfiguration _config;
- private EmployeeServiceClient _client = null;
-
- public Worker(ILogger<Worker> logger, IConfiguration config)
- {
- _logger = logger;
- _config = config;
- }
-
- protected EmployeeServiceClient Client
- {
- get
- {
- if (_client == null)
- {
- var channel = GrpcChannel.ForAddress(_config["gRPCService:ServiceUrl"]);
- _client = new EmployeeServiceClient(channel);
- }
- return _client;
- }
- }
-
- protected override Task ExecuteAsync(CancellationToken stoppingToken)
- {
- var result = Client.GetAllEmployee(new Empty());
-
- Console.WriteLine($"Result From Worker Service: {result}");
-
- Console.WriteLine("Press a key to exit");
- Console.ReadKey();
-
- return Task.FromResult(result);
- }
- }
Step 12
Run the gRPC server application and then run the “TestWorkServiceClient” project, messages consumed in worker service client.
Summary
In this post, we have learned how we can create gRPC Client application in .Net core. Creating a separate gRPC client library helps reuse different gRPC client applications.
We don’t need to add gRPC dependent libraries to each of the gRPC client application if we used one common client library.