Introduction of gRPC in .NET
What is gRPC
RPC : A technique to construct distributed client-server based applications , it is like you make an local call but it invokes something at that distributed machine and sends you a response
gRPC is a modern open source high performance Remote Procedure Call (RPC) framework , g stands for Google.
gRPC vs REST
Let’s see some differences b/w these two protocols:
- Protocol: gRPC uses HTTP/2, while REST uses HTTP/1.1
- Data Format: gRPC uses protocol buffers; REST uses JSON/XML
- Streaming: gRPC supports bidirectional streaming; REST uses a request/response model
- Performance: gRPC generally performs better than REST
Benefits of gRPC
gRPC offers several advantages:
-
It is faster because it uses protocol buffers.
-
It supports multiple languages making it a tool of choice for polyglot languages.
Polyglot : using multiple programming languages to serve different tasks
-
It supports four types of communication (Unary , server streaming , client streaming and bi directional streaming).
Implementation in .NET 6.0
Here’s how to implement gRPC in .NET 6.0:
Step 1: Create a project of type ‘ASP.NET Core gRPC Service’. This will act as the server.
Step 2: Within same solution add another project , for example a console application. This will act as client
Your solution will look like this:
Understanding Server Side
Let’s see Protos folder which contain a proto file whose code looks like this :
syntax = "proto3";
option csharp_namespace = "GrpcService";
package greet;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
This file defines how are you going to communicate , ignore first three lines.
HelloReply
: In simple words it is a DTO written in proto buffer style , which says that the response that server will send to client will contain these properties.HelloRequest
: When a client will send request to server the request will contain properties mentioned in this message.
Ordering in reply and request is giving instruction that properties would be in this order. You can change these names as well.
service Greeter
: This part is responsible for rpc and it takes a request in parameter and returns the response.
Let’s see Services folder which contain a .cs file whose code looks like this : public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
Request will contains the properties which we defined in our proto.
Greeter.GreeterBase : it is an auto created class and its name would be what you define in your proto (for our example service Greeter)
Last part is how the cs project file looks like for Server:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.40.0" />
</ItemGroup>
</Project>
Understanding Client Side
Client side which is a console application is empty right now with only one file of Program.cs , install these three Nuget Packages which are necessary to communicate with server.
Next step is copy the proto buffer file from server and paste it on client side by creating a new folder of Protos.
Change namespace in proto file and replace ItemGroup of client with this code
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="client" />
</ItemGroup>
We are telling that this proto is for client purposes.
Last important thing is just click on proto files in client and server side and open its properties and perform these two actions
—> Set BuildAction to Protobuf compiler
—> Set gRPC Stub Classes to Server Only for Server and Client Only for Client
Let’s add client side code now to communicate with server
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var response = await client.SayHelloAsync(new HelloRequest
{
Name = "World"
});
Console.WriteLine(response.Message);
In ForAddress we have added server address which is address of where our server app is running , one thing is important to keep in mind that we have not added any reference b/w client and server project.
That is all you need to do now set both projects to run at start by right clicking on solution —> Configure start up project —> Set multiple
When to use gRPC in .NET
- Microservices Architecture: Ideal due to its small, fast, and efficient binary size.
- Real-Time Applications: Perfect for real-time and streaming applications with bidirectional streaming support.
- Polyglot Environments: Useful for applications needing to communicate with services in multiple languages.
You can download demo code from my GitHub Repo
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place