Grpc example in c#

Lets follow below steps to create 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 proto file also. I would recommend you to please go through this post if you don’t know about protobuf. This example is divided in two parts. 1. Service and 2. Consumer.

Service implementation

  1. Create blank solution and name it as “GrpcServiceExample”
1
2

2. Add (console type) new project under created solution and name it as “GrpcServiceExample.ReverseService”

3
4

3. In service, add these nuget packages. All these nuget packages help us in compiling proto files and generating boiler plate code for us.
A) Google.Protobuf,
B) Grpc.Core,
C) Grpc.Tools

5

4. Create folder called “protos” and add new file “reverseservicecontract.proto” in that folder.

6

5. Lets add service and contract definition in created proto file. here, Service name is “RevService”. Method name is “Reverse”. This method takes Data message as input and return same message.

7

6. After adding above contracts in proto file, when you will build, build won’t be successful. By default, proto file compile through 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”.

8

7. In proto file, we have just declare the contracts but we need to provide those contrtacts definition also. so lets implement service and its method definition. Here, “RevServiceBase” is automated generated code by Grpc.

9

8. After implementation of all contracts, we need to define server. We need to define its host name, port etc. so client can reach to that service on defined address. You can also provide secure connection if needed by providing certificate. This service will run on 11111 port so client can reach to this service on this port only.

10

9. In Program.Main method, lets start above created server otherwise no consumer can access this service.

14

Consumer

  1. Lets add another console app project in same solution or in another solution called “GrpcServiceExample.Consumer”
11

2. Lets add all 3 nuget packages in consumer project also

12

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

4. Lets create client which will call implemented service. We need to call service on address.

17

5. Lets start server first and then run client.

16
15

I’ve created another simple example of Grpc here.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *