liveBook · Manning

Code generation

As explained in Building Web APIs with ASP.NET Core

Code generation is the automated production of source code or compiled code from a higher-level specification.

Code generation automates the production of client and server stubs from a higher-level protocol definition. In a .NET gRPC service, a protobuf file describes the service, requests, and responses; the project file then tells the compiler to generate the corresponding code. section 10.3.4

A practical implementation follows these steps:

  • Define the gRPC service and message shapes in grpc.proto, including the GetBoardGame method and BoardGameRequest and BoardGameResponse messages. section 10.3.4
  • Add a Protobuf item to the project file so the .NET compiler locates and compiles the definition. section 10.3.4
  • Implement the generated base class in GrpcService.cs, retrieve the requested board game, and return a generated response type. section 10.3.4
  • Register gRPC services and map the service endpoint in Program.cs. section 10.3.4

Board-game API

The grpc.proto contract declares GetBoardGame. Generated types provide the request, response, and service base class, while GrpcService supplies the database query and response behavior. section 10.3.4

Listing 10.7 /gRPC/grpc.proto file
syntax = "proto3";
 
option csharp_namespace = "MyBGList.gRPC";
 
package Grpc;
 
service Grpc {
  rpc GetBoardGame (BoardGameRequest) returns (BoardGameResponse);   #1
}
 
message BoardGameRequest {                                           #2
  int32 id = 1;
}
 
message BoardGameResponse {                                          #3
  int32 id = 1;
  string name = 2;
  int32 year = 3;
}

Inspect the protobuf contract that drives generation, including the RPC method and message field indexes. section 10.3.4

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains contract definition, project configuration, service implementation, and endpoint registration without detailing generator internals.
Examples
Uses a grpc.proto contract, a csproj Protobuf entry, GrpcService.cs, and Program.cs registrations for a board-game endpoint.
What you can do after
Build a gRPC endpoint from a protobuf definition and connect its generated types to application data.
How it connects
Connects Protocol Buffers, gRPC, C#, the .NET compiler, generated stubs, and service registration.

Also explained in

Compare how 17 books explain code generation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.