gRPC Example in C#

Introduction 

Let's follow the below steps to create a simple gRPC service in C#. This service will have a simple method called “Reverse” which will take one string parameter and return reverse of that string. This example contains a proto file also. I would recommend you to please go through this post if you don’t know about protobuf. This example is divided into two parts: 1. Service and 2. Consumer.

Service implementation

1. Create a blank solution and name it “GrpcServiceExample”
 
       
 
       
 
2. Add (console type) new project under created solution and name it “GrpcServiceExample.ReverseService”
 
       
 
       
 
3. In services, add these NuGet packages. All these packages help us in compiling proto files and generating boilerplate code for us.
      A) Google.Protobuf
      B) Grpc.Core
      C) Grpc.Tools
 
       
 
4. Create a folder called “protos” and add a new file “reverseservicecontract.proto” in that folder.
 
       
 
5. Let's add service and contract definition in created proto file. Here, the service name is “RevService”. The method name is “Reverse”. This method takes Data message as input and returns the same message. 
 
       
 
6. After adding the above contracts in the proto file, when you build, the build won’t be successful. By default, the proto file compiles through the C# compiler. So we need to change it to “protobuf compiler”. Right-click on proto file, click on “Properties” and change Build Action to “Protobuf compiler”.
 
       
 
       
7. In the proto file, we have just declared the contracts, but we need to provide the contract definition also. Let's implement service and its method definition. Here, “RevServiceBase” is an automated generated code by gRPC.
 
       
 
8. After the implementation of all contracts, we need to define the server. We need to define its hostname, port, etc. so the client can reach to that service on the defined address. You can also provide a secure connection if needed by providing a certificate. This service will run on 11111 port so the client can reach the service on this port only.
 
       
 
9. In the Program.Main method, let's start the above-created server, otherwise, no consumer can access this service.
 
       
 
      

Consumer

Let's add another console app project in the same solution or in another solution called “GrpcServiceExample.Consumer”
 
       
 
       
2. Let's add all 3 NuGet packages in the consumer project also.
 
       
 
       

3. Add “protos” folder in the consumer project and add the same proto file in the consumer. Also, change its build action to “Protobuf compiler” and build a consumer project.

4. Let's create a client which will call implemented service. We need to call a service on the address.

       
 
      

5. Let's start the server first and then run the client.

       
 
       

I’ve created another simple example of gRPC here.

Happy coding!