gRPC Using C# And .Net Core - Day One

.Net Core 3.0 has been launched last month and one of the major features of it is gRPC. Let’s have a detailed discussion on how to get started with gRPC using C# and .Net Core. Let’s divide our article into the following sections,
 
Agenda
  1. What is GRPC
  2. GRPC Vs REST
  3. Creating GRPC Service
  4. Creating GRPC Client
  5. WCF to GRPC
  6. Conclusion

What is gRPC

 
According to official blog “GRPC is a open source high performance RPC framework that can run in any environment, it can efficiently connect services across data centers with support of load balancing, tracing and authentication.” Mostly gRPC is used for connecting polyglot services in microservices architecture, connecting mobile devices, browser clients to the services
 
Grpc has two parts the -- gRPC protocol and data serialization. By default gRPC uses Protobuf for the serialization and protocol is based on Http2 which provides a lot of advantages over traditional Http1.x
 

GRPC vs REST

 
REST has been one of the concrete pillars of the web programming recently, but the emergence of the gRPC has put some challenge before REST. The below tables explain the differences between them,
 
Parameter
REST
gRPC
Serialization
JSON/XML
protobuf
Protocol
HTTP/1.1
HTTP/2.0
Browser Support
Yes
No
Data Exchange
Resources and Verbs
Messages
Request-Response Model
Only supports Request Response as based on Http/1.1
Supports All Types Of Streaming as based on Http/2
Payload Exchange Format
Serialization like JSON/XML
Strong Typing
 

Creating GRPC Service

 
As we are good with the basics, for now, let’s move and see how we can create the Service, and later  let’s see how we can consume that service into the client. To get started with the service we need to have a few initial things as follows
  1. Visual Studio 2019
  2. .NET Core SDK 3.1
Once you have this we can follow the following steps to create our first service
 
Add New Project and Select the GRPC Service as a new project
 
NewProjectAdd
 
In our case, we are adding a Project with name ToDoGrpcService, when we will add the Project we will have the following Structure,
 
Pstructure
 
Our project will be added with the default Greet service and One Default greet. Proto File.
 
In this Project, we are going to create our first To-do. Grpc Service for that first we need to add the proto file like below.
 
Right Click on Protos Folder -> Add New Item -> Select ProtoBuff File and name it "ToDo" like below,
 
 

Creating ProtoBuff Service Contract and Schema

 
Grpc uses Proto File to define the service contracts and it also contains the schema for the data which will be sent across between the services. Our ToDo service will have the following code,
  1. syntax = "proto3";  
  2. option csharp_namespace = "ToDoProtos";  
  3.   
  4. service ToDoService{  
  5. rpc getToDoItem(google.protobuf.Empty) returns (ToDoModel);  
  6. }  
  7.   
  8. message ToDoModel{  
  9.     string Title=1;;  
  10.     string Description=2;  
  11.     bool status=3;  
  12. }  
Code Explanation
  1. The first line specifies the version of Protobuff used in the programs; i.e. Proto3
  2. The second line specifies the Namespace under which this service will be created
  3. The next section specifies the actual service name and the Method into the Service. In our case our service is ToDoService and we have getToDoItem Method with empty parameter and returns the ToDoModel
  4. The last section is the actual data which will be returned from the service

Creating Server

 
Once we are done with adding the proto buff file we are ready to create the server. In this server we will use the automatically generated code from the protobuff file. We can stub out the functionality over the code which handles the communication and serialization.
 
To generate the code from the protobuf file we need to make the changes in the .csproj file of our project and add lines like below,
 
 

Implementing the Service


The next step in creating a service is to create a class that will be inherited from the above-generated class and implement the service contract that we have defined in the protobuff file above. Once implemented it will look like below
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Google.Protobuf.WellKnownTypes;  
  6. using Grpc.Core;  
  7. using ToDoProtos;  
  8.   
  9. namespace SampleGrpcService.Services  
  10. {  
  11.     public class ToDoDataService: ToDoProtos.ToDoService.ToDoServiceBase  
  12.     {  
  13.         public override Task<ToDoModel> getToDoItem(Empty request, ServerCallContext context)  
  14.         {  
  15.             return Task.FromResult(GetToDoData());  
  16.         }  
  17.   
  18.         public ToDoModel GetToDoData()  
  19.         {  
  20.             return new ToDoModel()  
  21.             {  
  22.                 Status = true,  
  23.                 Description = "First Grpc Service",  
  24.                 Title = "Grpc Service"  
  25.             };  
  26.         }  
  27.     }}  
This will complete our steps for the creation of our first grpc service. Now it’s time to create a client which will consume this service and show us the output. Before that let's run the application using console using command dotnet Run
 

Startup and Configure Services changes

 
After making changes in the startup section the code will look like below. In this we have to map our endpoints to the services which we have generated and we have to tell the application that we are going to use the grpc as a service in the application. 
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddGrpc();  
  4. }  
  5.   
  6. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  7. {  
  8.     if (env.IsDevelopment())  
  9.     {  
  10.         app.UseDeveloperExceptionPage();  
  11.     }  
  12.   
  13.     app.UseRouting();  
  14.   
  15.     app.UseEndpoints(endpoints =>  
  16.     {  
  17.         endpoints.MapGrpcService<GreeterService>();  
  18.         endpoints.MapGrpcService< SampleGrpcService.Services.ToDoDataService>();  
  19.         endpoints.MapGet("/", async context =>  
  20.         {  
  21.             await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");  
  22.         });  
  23.     });  
  24. }  

Creating Client

 
To create a client let's add the console application like usual. Once the application is added let's add following three packages in the project,
  1. Google.Protobuf
  2. Grpc.Net.Client
  3. Grpc.Tools
Next thing that we need to do in the client project is to add the Proto file that we have generated already. Again we have to modify .csproj file to generate a stub for the client code that we want to use in the application like below
  1. <ItemGroup>  
  2.   
  3. <Protobuf Include="Protos\ToDo.proto" GrpcServices="Client" />  
  4.   
  5. </ItemGroup>  
Next step is to add the client code which will call the service. The code will be like below in which we create a channel pointing to an address where our service will be hosted and next we will have a client-generated from the proto file. It will have a Method which will be called just like we call a class Method.
  1. using System;  
  2.   
  3. namespace TodoGrpcClient  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             var channel = Grpc.Net.Client.GrpcChannel.ForAddress("https://localhost:5001/");  
  10.   
  11.             var client = new ToDoProtos.ToDoService.ToDoServiceClient(channel);  
  12.             var request = new Google.Protobuf.WellKnownTypes.Empty();  
  13.             var result = client.getToDoItem(request);  
  14.             Console.WriteLine(result.Description);  
  15.             Console.WriteLine(result.Status);  
  16.             Console.WriteLine(result.Title);  
  17.   
  18.             Console.ReadKey();  
  19.         }  
  20.     }  
  21. }  
Just set the client project as a startup project and run the application and we can see the output as below,
 
 
This was all about creating the client for the Grpc Service
 

WCF to GRPC

 
One of the alternatives as recommended by Microsoft is to use the Grpc instead of the WCF services in the future projects. In this section, let us see how we can relate our understanding of the WCF to the Grpc concepts that we have right now,
 
WCF
Grpc
ServiceContract
Service in ProtoFile
OperationContract
RPC Method in ProtoFile
DataContract
Message in the ProtoFile
FaultContract
Richer error Model
Request-Reply
Unary Streaming
Duplex
Bidirectional Streaming
 

Conclusion

 
This was all about creating your first Grpc Service using C# and Asp.net core. You can find the code attached to the article for you. 
 
References
  1. https://docs.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/
  2. https://docs.microsoft.com/en-us/aspnet/core/grpc/?view=aspnetcore-3.0
  3. https://grpc.io/docs/guides/


Similar Articles