Search code examples
c#grpcprotogrpc-c#

How to create proper autogenerated code in C# for gRPC?


I created a proto file in a C# Project and tried to auto-generate C# codes by building the solution. But, I have an issue with the file under the extension grpc.cs.

''' 

/// <summary>Creates a new client for Greeter</summary>
   /// <param name="channel">The channel to use to make remote calls.</param>
      public GreeterClient(grpc::Channel channel) : base(channel)
      {
      }

'''

The above snip is from the example, where the public GreeterClient has the parameter (grpc::Channel channel) But in the below snip, it's (grpc::ChannelBase channel)

'''

/// <summary>Creates a new client for samples</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public samplesClient(grpc::ChannelBase channel) : base(channel)
{
}

'''

This throws an error telling 'Client Channel can't be found

How to configure and generate the grpc.cs file so that the parameter is (grpc::Channel channel)


Solution

  • I'm not sure what are you doing (...tried to autogenerate... <- you mean you running protoc manually ? Why ?)

    This is an example for .NET Framework project, .NET Core created slight different - here is excelent resource to get started for .NET Core: ASP.NET Core gRPC for WCF Developers

    Usually what you do

    1. Create project and install relevant Nuget packages: Grpc, Grpc.Core and most importantly the Grpc.Tools package
    2. Add new file. Name it whetever you want but extension must be .proto
    3. Fill some data inside this proto file like:
    syntax = "proto3";
    
    option csharp_namespace = "MyNamespace";
    
    ...
    ...
    
    1. Right mouse click on this file and select Properties
    2. In the 'Properties' panel select Protobuf as a Build action. So it should look like this:

    enter image description here

    1. Rebuild the solution
    2. Add another C# file, name it anything you want
    3. In this C# file start referencing the structures you created in proto file. Like:

    MyNamespace.MyServer server = new MyNamespace.MyServer()

    but actually you should inherit from base class that ptotobuf created for you like this:

     public class GrpcImplementationClass: MyNamespace.MyServer.MyServerBase
     {
    
       public override MyFunction()
       {
       ...
       ...
    

    P.S. There's a lot of tutorials for beginnners on Youtube