A gRPC service is a remotely callable API defined in a Protocol Buffers file. The file describes services and messages; generated bindings provide a server base class that an application extends. section 10.3.4
Implement a gRPC service in four practical steps:
- Create a grpc.proto file using proto3, then define an RPC such as GetBoardGame with request and response message types. section 10.3.4
- Register the .proto file in the project file so the .NET compiler generates client and server stubs. section 10.3.4
- Extend the generated service base class, inject ApplicationDbContext, query EF Core, and populate the response. section 10.3.4
- Register gRPC services and map the concrete service into the HTTP pipeline. 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;
}
Use the protocol definition to inspect the RPC contract and its DTO-like request and response messages. section 10.3.4
Listing 10.8 /gRPC/GrpcService.cs file
using Grpc.Core;
using Microsoft.EntityFrameworkCore;
using MyBGList.Models;
namespace MyBGList.gRPC
{
public class GrpcService : Grpc.GrpcBase #1
{
private readonly ApplicationDbContext _context; #2
public GrpcService(ApplicationDbContext context)
{
_context = context; #2
}
public override async Task<BoardGameResponse> GetBoardGame( #3
BoardGameRequest request,
ServerCallContext scc)
{
var bg = await _context.BoardGames #4
.Where(bg => bg.Id == request.Id)
.FirstOrDefaultAsync();
var response = new BoardGameResponse();
if (bg != null)
{
response.Id = bg.Id;
response.Name = bg.Name;
response.Year = bg.Year;
}
return response; #5
}
}
}
Use the service implementation to follow request handling, database lookup, and response construction. section 10.3.4
