GRPC with ASP.NET Core from scratch

Jaroslaw Janiszewski
6 min readJun 6, 2020

--

Overview

In this tutorial, you will find out what gRPC is and how to use it in .NET Core to create powerful microservices. Throughout the article, you will build a sample service with a client that will dive into the details of using gRPC in C#. Finally, the whole project is in the GitHub repository.

Introduction

If we create software that will be selling for clients include services architecture then we need to think whether communication-based on message broker is meet our requirements.
Sometimes communication-based on message broker has disadvantages if we want to install architecture on the client’s infrastructure like hospitals. Hospital IT staff usually doesn’t have enough knowledge to maintain it. gRPC protocol will come to help us with this problem

gRPC means Google Remote Procedure Call, was developed by Google in 2015 and released in August 2016. gRPC runs exclusively HTTP / 2 and uses protocol buffers as the interface description language.

Protocol gRPC has features such as:

  • It is optimized for speed and size.
  • It is ideal for low resource clients (e.g. IoT), microservices.
  • Always runs over a secure connection (e.g. HTTPS, TLS).
  • It does not support multicasting (see SignalR).
  • Supports unidirectional and bidirectional streaming.
  • It is good at queuing and messaging.
  • Not easy to read by people.

Below is shown overall architecture of a system using gRPC protocol:

Comparing with other protocols

It doesn’t exist one protocol which is the best. Every protocol is doing a good job for some specific areas. Below are an example of compared protocols and how gRPC is fitted into this comparison:

  • SignalR — for a solution that requires frequent updates and notification,
  • REST — for web apps using CRUD methods,
  • GraphQL — create a custom query that allows you to get what you need from a large dataset,
  • gRPC — a low-level protocol that allows connection services inside and between data centers.
Example of using protocols in services architectures

Comparing the size of messages between JSON and Protobuf

The size of messages is one of an important aspect that should be taken into account during analyzing performance issue. The following diagram show comparison of messages size between JSON and Protobuf:

The above diagram clearly illustrates that message size using gRPC takes much fewer bytes. For example, a first message using Protobuf binary format consumes 25 bytes against 102 bytes using JSON protocol. So it’s cleary that gRPC message size takes around 24,5 % of the size used by JSON. Much more difference is when we want to send 20 messages. gRPC takes 253 bytes against 724 bytes using JSON. It reducted 65,1% size. To reduce JSON content size we can compress message by using GZIP but it’s a requirement to use additional CPU time to zip content.

ASP.NET Core Web API with gRPC

This example will be created a simple service-client app that will get a pseudo-random weather forecast for some specific region.

Structure gRPC in .NET CORE

gRPC protocol is divided into several libraries that are used by microservices. These libs are storing as NuGet packages. What we need is only to download the proper NuGet package into our project.

Below is shown the structure of libraries by NuGet packages:

Service with gRPC

It exists two possibilities to add gRPC to the project. First, the easiest one is to create a new project from the Visual Studio template. Only what should do is type in the name “gRPC” on the search textbox.

Create a new project using gRPC Service

The second option is to add gRPC to the existing project. The only required action is to download the NuGet package to the project. It’s needed to download “Grpc.AspNetCore” as shown below:

Grpc.AspNetCore NuGet package

Next step is to invoke “AddGrpc” method in “ConfigureServices” in “Startup” class like below:

Startup.cs in the service app

The last step is to add a folder to our project called “Protos”. It will contain proto files.

Now the project is integrated with gRPC protocol. We can start programming weather forecast service. The first action is to add the proto file called “weather.proto”.

Add Proto file

Proto file contains a declaration of services with requests and response messages type that compiled by protoc (for more information on proto-language you can find here https://bit.ly/3d2RoTy ). After added proto file select this file and then in “Properties view” change options as shown below:

Properties of weather.proto

Build action should be set on “protobuf compiler” and gRPC stub classes on “server only

In weather.proto type in the below syntax:

Weather.proto in the service app

Weather.proto file contains several important information. Service “WeatherService” has a method called “GetWeatherForecast” which gets weather forecast. It takes one parameter “WeatherForecastRequest” that defines the city and period of time. Method response “WeatherForecastResponse” object. It contains a collection of WeatherForecastItem which storing information such as city, date, Kelvin and Celsius temperature and summary.

The next step is to add a class called “WeatherForecastService” to a project that implements this method. Below is shown of implementation of this service:

WeatherForecastService class in the service app

One of the interesting things is that the class “WeatherForecastService” inherits from “WeatherService” which is defined in the proto file. The class also contains a definition of method “GetWeatherForecast” that declaration is also in the proto file.

Client with gRPC

For this example is used simple console application as a client. To connect between client and server only what take action is add the same proto file to a client that is using in the server app. To do this is to choose the option “add connected service” from the context menu.

In section “Service References” click add button, then in selection type of service choose gRPC option as shown below:

Select a service reference to add to your application

In the section “Select a file or URL” select file option and then browse the proto file that is inside the in-service project. The next action chooses the “Client” option from “Select the type of class to be generated”. The last action is to click the “Finish” button.

Select a file or URL

As we can see in the client app is added a proto file that is in the Protos folder. It’s exactly the same as what is in the service app. In the background was downloaded NuGet packages for gRPC. The last thing that is needed is to add a snippet of code that is using gRPC protocol.

Programs class in a client app

The main method contains some interesting parts. First is created gRPC channel from the address “https: // localhost: 5001”. The next step is to create a client instance base on “WeatherService” that is declared in a proto file. Method “WeatherServiceClient” takes channel instance as an argument. Next is created a request instance that takes arguments like city name and time interval. The next action is invoked asynchronously method “WeatherForecastRequest”. The last code is responsible to show results.

Demo using gRPC protocol you can find in GitHub below:

Summary

As we see create and maintenance apps using gRPC is pretty simple. This protocol gives us many advantages mentioned in this article.
I hope I encourage you to start exploring more features that it delivered this protocol.

--

--