Create gRPC Consoles And WorkerService Client Applications

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:
 
Create gRPC Consolse And WorkerService Client Applications 
 
Step 2
 
We need to install below Nuget Libraries for gRPC client application.
 
Libraries
  • Google.Protobuf
  • Grpc.Net.ClientFactory
  • Grpc.Tools
Create gRPC Consolse And WorkerService Client Applications
 
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.
  1. syntax = "proto3";  
  2. import "google/protobuf/empty.proto";  
  3. import "google/protobuf/Timestamp.proto";  
  4.   
  5. option csharp_namespace = "TestService.Protos";  
  6.   
  7. service EmployeeService{    
  8.    rpc GetAllEmployee(google.protobuf.Empty) returns (ResponseMessage);    
  9. }  
  10.   
  11. message EmployeeModel{    
  12.     google.protobuf.Timestamp dateTimeStamp = 1;  
  13.     string name=2;    
  14.     string skill=3;    
  15.     string email=4;    
  16. }    
  17.   
  18. message ResponseMessage{  
  19.     string message=1;  
  20.     bool success=2;  
  21.     repeated EmployeeModel employees=3;  
  22. }  
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.
 
Create gRPC Consolse And WorkerService Client Applications 
 
Step 5
 
Once we build the application, we can verify the auto-generated files “Employee.cs” and “EmployeeGrpc.cs” in “obj/Debug” folder.
 
Create gRPC Consolse And WorkerService Client Applications 
 
Step 6
 
Create a console application and add our “TestClient.GRPC.ClientLib” library project to the consoles' applications:
 
Create gRPC Consolse And WorkerService Client 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. 
  1. namespace TestConsoleClient  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             using var channel = GrpcChannel.ForAddress("https://localhost:5001");  
  8.   
  9.             var client = new EmployeeServiceClient(channel);  
  10.   
  11.             var reply = client.GetAllEmployee(new Empty());  
  12.   
  13.             Console.WriteLine($"Result: {reply}");  
  14.   
  15.             Console.WriteLine("Press a key to exit");  
  16.             Console.ReadKey();  
  17.         }  
  18.     }  
  19. }  
 
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”.
 
Create gRPC Consolse And WorkerService Client Applications
 
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.
 
Create gRPC Consolse And WorkerService Client Applications
 
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.
 
Create gRPC Consolse And WorkerService Client Applications 
 
Step 10
 
After creating the “TestWorkServiceClient” project, add a reference to the “TestClient.GRPC.ClientLib” library project.
 
Create gRPC Consolse And WorkerService Client Applications
 
Step 11
 
In Appsettings.json files add the below configuration. We will use the below configuration in the next step.
  1. "gRPCService": {    
  2.    "ServiceUrl""https://localhost:5001"    
  3. }  
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.
  1. protected EmployeeServiceClient Client  
  2. {  
  3.    get  
  4.    {  
  5.       if (_client == null)  
  6.       {  
  7.          var channel = GrpcChannel.ForAddress(_config["gRPCService:ServiceUrl"]);  
  8.          _client = new EmployeeServiceClient(channel);  
  9.       }  
  10.       return _client;  
  11.    }  
  12. }  
“ExecuteAsync” method has the below code to access the gRPC method:
  1. var result = Client.GetAllEmployee(new Empty());  
Below, the worker service code has been added for your reference:
  1. public class Worker : BackgroundService  
  2.   {  
  3.       private readonly ILogger<Worker> _logger;  
  4.       private readonly IConfiguration _config;  
  5.       private EmployeeServiceClient _client = null;  
  6.   
  7.       public Worker(ILogger<Worker> logger, IConfiguration config)  
  8.       {  
  9.           _logger = logger;  
  10.           _config = config;  
  11.       }  
  12.   
  13.       protected EmployeeServiceClient Client  
  14.       {  
  15.           get  
  16.           {  
  17.               if (_client == null)  
  18.               {  
  19.                   var channel = GrpcChannel.ForAddress(_config["gRPCService:ServiceUrl"]);  
  20.                   _client = new EmployeeServiceClient(channel);  
  21.               }  
  22.               return _client;  
  23.           }  
  24.       }  
  25.   
  26.       protected override Task ExecuteAsync(CancellationToken stoppingToken)  
  27.       {  
  28.           var result = Client.GetAllEmployee(new Empty());  
  29.   
  30.           Console.WriteLine($"Result From Worker Service: {result}");  
  31.   
  32.           Console.WriteLine("Press a key to exit");  
  33.           Console.ReadKey();  
  34.   
  35.           return Task.FromResult(result);  
  36.       }  
  37.   }  
Step 12
 
Run the gRPC server application and then run the “TestWorkServiceClient” project, messages consumed in worker service client.
 
Create gRPC Consolse And WorkerService Client Applications 
 

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.