Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Microservices Communication in .NET Using gRPC

You're reading from   Microservices Communication in .NET Using gRPC A practical guide for .NET developers to build efficient communication mechanism for distributed apps

Arrow left icon
Product type Paperback
Published in Feb 2022
Publisher Packt
ISBN-13 9781803236438
Length 486 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Fiodar Sazanavets Fiodar Sazanavets
Author Profile Icon Fiodar Sazanavets
Fiodar Sazanavets
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Section 1: Basics of gRPC on .NET
2. Chapter 1: Creating a Basic gRPC Application on ASP.NET Core FREE CHAPTER 3. Chapter 2: When gRPC Is the Best Tool and When It Isn't 4. Chapter 3: Protobuf – the Communication Protocol of gRPC 5. Section 2: Best Practices of Using gRPC
6. Chapter 4: Performance Best Practices for Using gRPC on .NET 7. Chapter 5: Applying Versioning to the gRPC API 8. Chapter 6: Scaling a gRPC Application 9. Section 3: In-Depth Look at gRPC on .NET
10. Chapter 7: Using Different Call Types Supported by gRPC 11. Chapter 8: Using Well-Known Types to Make Protobuf More Handy 12. Chapter 9: Securing gRPC Endpoints in Your ASP.NET Core Application with SSL/TLS 13. Chapter 10: Applying Authentication and Authorization to gRPC Endpoints 14. Chapter 11: Using Logging, Metrics, and Debugging in gRPC on .NET 15. Assessments 16. Other Books You May Enjoy

Understanding how proto files generate C# code

Normally, you wouldn't need to worry about how C# classes are generated from proto files. The compiler does it all for you. But occasionally, there may be a problem with the process. Therefore, it would be useful to know how to find the generated code and what the expected output should be.

Where is auto-generated code stored?

At this point, you know that the .NET compiler generates code from the proto files. This can then be referenced from inside your application code. And you can also get it to share the same namespace as your application. But despite the ability of this code to inter-operate with your application code, it's not part of your application.

The auto-generated code is placed in the obj folder inside your project folder. The purpose of this folder is to store intermediate resources that are required to compile your application. Since auto-generated classes aren't part of your main application, but your application cannot be compiled without them, they are placed alongside other intermediate files in this folder.

More precisely, the location of those auto-generated files is as follows. This represents the path on the Windows system. For a Unix-based system, such as macOS or Linux, replace back-slashes (\) with forward-slashes (/):

{your project folder}\obj\{build configuration}\{framework 
  name}\Ptotos

So, for our BasicGrpcService project, which is based on .NET 5's built-in Debug mode, the path would be as follows:

BasicGrpcService\obj\Debug\net5.0\Ptotos

For each proto file that you reference in your project, a pair of files containing C# code will be generated:

  • {PascalCase proto file name}.cs
  • {PascalCase proto file name}Grpc.cs

The {PascalCase proto file name}.cs file contains a C# representation of the proto messages that your services use, while {PascalCased proto file name}Grpc.cs contains a C# representation of the services themselves, whether it's overridable base classes for the server or ready-made classes for the client.

In our example, which uses the greeter.proto file, we would end up with two files with the following names:

  • Greeter.cs
  • GreeterGrpc.cs

The content of those auto-generated files would be similar to the following:

Figure 1.11 – An example of auto-generated gRPC C# code

Figure 1.11 – An example of auto-generated gRPC C# code

You can examine the structure of these files if you like. Now, let's learn how making changes to the namespaces in Protobuf will affect the auto-generated code.

Modifying Protobuf namespaces

So far, we have been using the csharp_namespace option inside our proto files to set the namespaces of auto-generated code classes to the same root namespace that our application uses. But it doesn't have to be this way. You can set the namespaces in auto-generated code to absolutely anything.

You can also omit the csharp_namespace option entirely. If you do so, the namespace that will be applied to your auto-generated code will be the PascalCase version of the package name that's specified in the package element of the proto file.

In our case, since the package is called greeter, the C# namespace that's generated from it will be Greeter.

Now, go ahead and remove the csharp_namespace element from both the client and server versions of the greeter.proto file. Both copies of the files should now look as follows:

syntax = "proto3";
 package greeter;
 
// The greetings manager service definition.
service GreetingsManager {
  // Request the service to generate a greeting message.
  rpc GenerateGreeting (GreetingRequest) returns 
    (GreetingResponse);
}
 
// The request message definition containing the name to be 
  addressed in the greeting message.
message GreetingRequest {
  string name = 1;
}
 
// The response message definition containing the greeting 
  text.
message GreetingResponse {
  string greetingMessage = 1;
}

Now, if you try to compile the projects, they will show errors. What you need to do is add a using statement to both the client and the server code referencing this namespace.

The content of the GreetingsManagerService.cs file inside the BasicGreeterService project should now look as follows:

using System.Threading.Tasks;
using Greeter;
using Grpc.Core;
namespace BasicGrpcService
{
     public class GreetingsManagerService : 
       GreetingsManager.GreetingsManagerBase
    {
        public override Task<GreetingResponse> 
          GenerateGreeting(GreetingRequest 
            request, ServerCallContext context)
        {
            return Task.FromResult(new GreetingResponse
            {
                GreetingMessage = "Hello " + request.Name
            });
        }
    }
}

The content of the Program.cs file inside the BasicGreeterClient project should now look as follows:

using System;
using System.Threading.Tasks;
using Greeter;
using Grpc.Net.Client;
namespace BasicGrpcClient
{
    class Program
    {
        static async Task Main()
        {
             // The port number(5001) must match the port of 
             the gRPC server.
             using var channel = 
               GrpcChannel.ForAddress("https://
                 localhost:5001");
             var client = new 
               GreetingsManager.
                 GreetingsManagerClient(channel);
             var reply = await client.GenerateGreetingAsync(
             new GreetingRequest { Name = "BasicGrpcClient" });
             Console.WriteLine("Greeting: " + 
               reply.GreetingMessage);
             Console.WriteLine("Press any key to exit...");
             Console.ReadKey();
        }
    }
}

Now, you know how easy it is to regenerate relevant code after making changes to the Protobuf definition. At this point, you have two copies of the greeter.proto file that are identical.

At this stage, you may be wondering whether having separate copies of this file would violate the don't repeat yourself (DRY) principle, which is a commonly accepted best practice when writing software. Will any problems occur if you update one of these files while forgetting to update the other? Isn't it possible to keep a single shared copy of the file that both the client and the server use?

Fortunately, you can share the same file between multiple applications in .NET. Let's have a look at how.

You have been reading a chapter from
Microservices Communication in .NET Using gRPC
Published in: Feb 2022
Publisher: Packt
ISBN-13: 9781803236438
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime