Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate .proto files or use 'Code First gRPC' in C#

I want to use gRPC with .NET in an asp.net core web application. How do I generate the necessary .proto file from an existing C# class and model objects? I don't want to re-write a .proto file that mirrors the existing code, I want the .proto file to be auto-generated from the class and model objects.

I call this method to register my service class.

builder.MapGrpcService<MyGrpcService>();

public class MyGrpcService
{
    public Task<string> ServiceMethod(ModelObject model, ServerCallContext context)
    {
        return Task.FromResult("It Worked");
    }
}

ModelObject has [DataContract] and [DataMember] with order attributes.

Is this possible? Every example I see online starts with a .proto file. I've already defined my desired service methods in the MyGrpcService class. But maybe this is just backwards to what is the standard way of doing things...

Something like the old .NET remoting would be ideal where you can just ask for an interface from a remote end point and it magically uses gRPC to communicate back and forth, but maybe that is too simplistic a view.

like image 516
jjxtra Avatar asked Nov 08 '19 14:11

jjxtra


People also ask

How does gRPC generate code?

The gRPC generated code starts by importing the grpc package and the plain _pb2 module, synthesized by protoc , which defines non-gRPC-specific code elements, like the classes corresponding to protocol buffers messages and descriptors used by reflection.

How do I add a gRPC to an existing project?

Right-click on your project, select Manage NuGet packages, find the Grpc. AspNetCore and Grpc. Tools packages and add them both to your project.


1 Answers

You can use Marc Gravell’s protobuf-net.Grpc for this. Having a code-first experience when building gRPC services is the exact use case why he started working on it. It builds on top of protobuf-net which already adds serialization capabilities between C# types and protobuf.

Check out the documentation to see how to get started using the library, or even watch Marc present this topic in one of the following recordings of his talk “Talking Between Services with gRPC and Other Tricks”:

  • Mark Gravell at .NET Oxford in September 2019
  • Marc Gravell at .NET Core Summer Event in June 2019

I think he actually updated the one in September for the release bits of .NET Core 3.0, so that would probably be the more updated version.

There are also a few code samples to see how this looks like when you set it up.

like image 140
poke Avatar answered Oct 11 '22 11:10

poke