How do you define a gRPC service contract using Protocol Buffers, and how is the C# service implementation generated from it?
Short answer
A .proto file defines the service's RPC methods and message types using protobuf syntax; the Grpc.Tools NuGet package's build-time code generation (via in the .csproj) automatically generates a strongly-typed C# base class (GreeterBase) that you inherit from and override to…
Advertisement
AModel answer
A .proto file defines the service's RPC methods and message types using protobuf syntax; the Grpc.Tools NuGet package's build-time code generation (via <Protobuf Include="..." /> in the .csproj) automatically generates a strongly-typed C# base class (GreeterBase) that you inherit from and override to implement the actual service logic, plus a strongly-typed client class for consumers.
// greet.proto
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
// GreeterService.cs -- inherits generated base class
public class GreeterService : Greeter.GreeterBase {
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) {
return Task.FromResult(new HelloReply { Message = $"Hello {request.Name}" });
}
}
// Program.cs
app.MapGrpcService<GreeterService>();Real-world example
A payments microservice defines its contract in a shared .proto file checked into a common repository, generating both the C# server implementation stub and client code automatically, ensuring server and client never drift out of sync on the contract shape.
Likely follow-ups
- How do you version a .proto contract without breaking existing clients?
- How is the generated code shared between multiple services/repositories?
Related topics