We are going to discuss the gRPC and its implementation using .NET Core 6

Agenda
    Introduction of gRPC
    Different scenarios in which we use gRPC
    Pros and Cons of gRPC
    Implementation of gRPC

Prerequisites

    Visual Studio 2022
    Basic Knowledge of C#

Introduction

    gRPC stands for Google Remote Procedure Calls
    gRPC is a modern open-source high-performance Remote Procedure Call (RPC) framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking, and authentication. It is also applicable in the last mile of distributed computing to connect devices, mobile applications, and browsers to backend services. – gRPC Page

 

    gRPC is the framework that is used to implement APIs using HTTP/2
    Basically, gRPC uses the protobuf for serialization and HTTP2 protocol which provides lots more advantages than HTTP
    gRPC clients and servers intercommunicate using a variety of environments and machines, It Also supports many languages like Java, C#, Go, Ruby and Python.
    The Binary layer of gRPC will do all data operations like encoding and it also uses protobuf as an intermediator between client and server, improving performance.
    It is also used for communication between multiple microservices efficiently

Different scenarios in which we use gRPC

    When we use microservice architecture and we use that for internal communication from one or more servers
    It is also useful when performance is on high priority and low latency
    When we require duplex communication between services with different types of data

Pros and Cons of gRPC
Pros
    High Performance - faster than REST and SOAP
    Lightweight Message - gRPC Message is more lightweight than other types like JSON
    High Efficiency than other type
    Duplex data streaming

Cons
    Limited Browser Support
    It uses Binary Data due that it’s not easily readable like JSON and XML

Implementation of gRPC

Step 1
Create a new gRPC project

Step 2
Configure the project


Step 3
Provide additional information

Step 4
Project Structure

Here you will see the default project structure with greet proto and Greeter Service

syntax = "proto3";

option csharp_namespace = "GrpcService";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

    Protobuf is Interface Definition Language (IDL) for gRPC and uses to store data and contracts between clients and servers
    Line No 1 to 5 as you see there we declare types of protobuf syntax, namespace, and package
    Line No 7 to 11 there is a Unary Service Definition which takes a single request and the server sends back the response and it works as a function
    There are also many service definitions like Server Streaming, Client Streaming, and Bidirectional streaming RPCs. If you want to learn more about then read the grpc.io document
    Later on, there is a request and response function in order

using Grpc.Core;
namespace GrpcService.Services
{
    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
            });
        }
    }
}


This is the Greeter Service which inherits from Greeter.GreeterBase and inside that we inject ILogger and there is one method which takes the message to send by the client and send back as a response

(Note: Build Application whenever you add a new proto and Service)

Also, make sure the proto property is configured properly as shown below

Here we can see Build Action Protobuf compiler and gRPC Stub Classes are Server only

Let’s create a Client Console Application

Step 1
Create a new console application


Step 2
configure your project

Step 3
provide additional information

Step 4

Copy greet proto file from the server and change the gRPC Stub Classes to Client only and build it

Step 5
Add client code inside the Program file

using Grpc.Net.Client;
using GrpcService;
using GrpcService.Protos;
var message = new HelloRequest {
    Name = "Jaydeep"
};
var channel = GrpcChannel.ForAddress("http://localhost:5045");
var client = new Greeter.GreeterClient(channel);
var srerveReply = await client.SayHelloAsync(message);
Console.WriteLine(srerveReply.Message);
Console.ReadLine();

    Here we create a channel after configuring the server’s URL and create a channel
    Later on, call the method after passing a parameter to the server and print the response message inside the console

Step 6
Finally, run your code after configuring your both project as startup projects in proper order

This is the final output
Now we are going to add our new proto and service related to the product application in that we pass the product id from the client and the server will send the particular product details back to the client

Step 1
Create a new product proto file and change properties to Protobuf compiler and Servers only after that build the project
syntax = "proto3";

option csharp_namespace = "GrpcService.Protos";

package product;

service Product {
    rpc GetProductsInformation (GetProductDetail) returns (ProductModel);
}

message GetProductDetail{
    int32 productId = 1;
}

message ProductModel{
    string productName = 1;
    string productDescription = 2;
    int32 productPrice = 3;
    int32 productStock = 4;
}

Here you can see, that we define service which takes product id as a parameter and send product details to the client

Step 2
Next, create a Product Service
using Grpc.Core;
using GrpcService.Protos;

namespace GrpcService.Services
{
    public class ProductService : Product.ProductBase
    {
        private readonly ILogger<ProductService> _logger;
        public ProductService(ILogger<ProductService> logger)
        {
            _logger = logger;
        }

        public override Task<ProductModel> GetProductsInformation(GetProductDetail request, ServerCallContext context)
        {
            ProductModel productDetail = new ProductModel();
            if (request.ProductId == 1)
            {
                productDetail.ProductName = "Samsung TV";
                productDetail.ProductDescription = "Smart TV";
                productDetail.ProductPrice = 35000;
                productDetail.ProductStock = 10;
            }
            else if (request.ProductId == 2)
            {
                productDetail.ProductName = "HP Laptop";
                productDetail.ProductDescription = "HP Pavilion";
                productDetail.ProductPrice = 55000;
                productDetail.ProductStock = 20;
            }
            else if (request.ProductId == 3)
            {
                productDetail.ProductName = "IPhone";
                productDetail.ProductDescription = "IPhone 12";
                productDetail.ProductPrice = 65000;
                productDetail.ProductStock = 30;
            }

            return Task.FromResult(productDetail);
        }
    }
}


Here you can see we create Product Service which inherits from Product.ProductBase and after that, we inject ILogger of type Product Service and create one method and inside that whatever product details client wants that we check and return as a response corresponding to the particular product which is sent by the client

Step 3
Map the Product Service inside the Program class
using GrpcService.Services;
var builder = WebApplication.CreateBuilder(args);
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
// Add services to the container.
builder.Services.AddGrpc();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapGrpcService < GreeterService > ();
app.MapGrpcService < ProductService > ();
app.MapGet("/", () => "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");
app.Run();


Step 4
Build Server Project

Step 5
Copy the Product protobuf file inside the client and change the properties to the client only
syntax = "proto3";
option csharp_namespace = "GrpcService.Protos";
package product;
service Product {
    rpc GetProductsInformation(GetProductDetail) returns(ProductModel);
}
message GetProductDetail {
    int32 productId = 1;
}
message ProductModel {
    string productName = 1;
    string productDescription = 2;
    int32 productPrice = 3;
    int32 productStock = 4;
}

Step 6
Next, add client functionality inside the Program class
using Grpc.Net.Client;
using GrpcService;
using GrpcService.Protos;
//var message = new HelloRequest { Name = "Jaydeep" };
//var channel = GrpcChannel.ForAddress("http://localhost:5045");
//var client = new Greeter.GreeterClient(channel);
//var srerveReply = await client.SayHelloAsync(message);
//Console.WriteLine(srerveReply.Message);
//Console.ReadLine();
var channel = GrpcChannel.ForAddress("http://localhost:5045");
var client = new Product.ProductClient(channel);
var product = new GetProductDetail {
    ProductId = 3
};
var serverReply = await client.GetProductsInformationAsync(product);
Console.WriteLine($ "{serverReply.ProductName} | {serverReply.ProductDescription} | {serverReply.ProductPrice} | {serverReply.ProductStock}");
Console.ReadLine();


Here we create a channel after configuring the server’s URL and after that create a model object with a user id and pass it to the method which gets the product details as a response. Finally, we just print the product details in the console

Step 7

Build and run your both projects after setting up as a startup project

So, this is the output of our service.

In this section, we just understand the basic working of gRPC with Product Application. But, in real-time scenarios, there are many ways to implement that like using Background service and some different gRPC streaming techniques that we discussed in upcoming articles

Conclusion
In this article, we discussed gRPC, Pros, and Cons of gRPC. Also, the scenarios in which gRPC plays an important role and step-by-step implementation using .NET Core 6

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.