Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

gRPC

Introduction

gRPC is a high-performance, open-source, universal RPC framework initially developed by Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and it provides features such as authentication, load balancing, and more. In this tutorial, we'll walk through creating and consuming gRPC services with .NET.

Prerequisites

  • Visual Studio installed with .NET development workload
  • Basic knowledge of .NET and C#

Creating a gRPC Service

First, create a new gRPC service project in Visual Studio:

  1. Open Visual Studio and click "Create a new project".
  2. Select "ASP.NET Core gRPC Service" and click "Next".
  3. Set the name and location for your project and click "Create".
  4. Choose the target framework (.NET 6) and click "Create".

Defining the gRPC Service

Define your gRPC service in a .proto file. Visual Studio will create a default greet.proto file in the Protos folder. Modify it as follows:

syntax = "proto3";

option csharp_namespace = "MyGrpcService";

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;
}

Implementing the Service

Implement the service by modifying the GreeterService.cs file in the Services folder:

using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.Extensions.Logging;

namespace MyGrpcService
{
    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
            });
        }
    }
}

Running the Service

Run the gRPC service by pressing F5 or clicking the "Start" button in Visual Studio. The service will be hosted on https://localhost:5001.

Creating a gRPC Client

Now, create a new .NET Console App to consume the gRPC service:

  1. Open Visual Studio and click "Create a new project".
  2. Select "Console App (.NET Core)" and click "Next".
  3. Set the name and location for your project and click "Create".
  4. Right-click on the project in Solution Explorer and select "Add" > "Service Reference".
  5. Choose "gRPC" and click "Next".
  6. Enter the URL of the gRPC service's .proto file (e.g., https://localhost:5001/protos/greet.proto) and click "Next".
  7. Click "Finish" to add the service reference.

Consuming the gRPC Service

Modify the Program.cs file to call the gRPC service:

using System;
using System.Threading.Tasks;
using Grpc.Net.Client;
using MyGrpcClient;

namespace MyGrpcClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The port number(5001) must match the port of the gRPC server.
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Greeter.GreeterClient(channel);
            var reply = await client.SayHelloAsync(new HelloRequest { Name = "World" });
            Console.WriteLine("Greeting: " + reply.Message);
        }
    }
}

Running the Client

Run the client application by pressing F5 or clicking the "Start" button in Visual Studio. You should see the greeting message from the gRPC service.

Conclusion

In this tutorial, we covered how to create and consume gRPC services with .NET. You learned how to define a gRPC service using Protocol Buffers, implement the service in .NET, and consume the service with a .NET client application. gRPC provides a powerful framework for building efficient, cross-platform, and language-agnostic APIs. Happy coding!