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.
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.
Right-click on your project, select Manage NuGet packages, find the Grpc. AspNetCore and Grpc. Tools packages and add them both to your project.
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”:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With