csharp

Google Remote Procedure Call

1. Server

Create Project

dotnet new grpc -n GrpcServer

Create category.proto

syntax = "proto3";
option csharp_namespace = "GrpcServer";
service CategoryService {
    rpc GetCategories(Empty) returns (CategoryList);
    rpc GetCategory(CategoryRequest) returns (CategoryResponse); 
}
message  Empty {
}
message AddCategoryRequest {
    string name = 1;
    string description =  2;
    string imageUrl = 3;
}
message EditCategoryRequest {
    int32 id = 1;
    string name = 2;
    string description =  3;
    string imageUrl = 4;
}
message  CategoryRequest {
    int32 id = 1;
}
message  CategoryResponse {
    int32 id = 1;
    string name = 2;
    string description =  3;
    string imageUrl = 4;
}
message  MessageResponse {
    int32 result = 1;
}
message  CategoryList {
  repeated CategoryResponse categories = 1;
}

Declare proto

Delare category.proto in GrpcServer.csproj

<Protobuf Include="Protos\category.proto" GrpcServices="Server" />

Category Service

Create class CategoryService in Services folder

using Grpc.Core;
using StoreGrpc.Models;
namespace StoreGrpc.Services;
public class CategoryService : StoreGrpc.CategoryService.CategoryServiceBase{
    SiteProvider provider;
    public CategoryService(SiteProvider provider) => this.provider = provider;
    public override async Task<CategoryList> GetCategories(Empty request, ServerCallContext context){
        CategoryList list = new CategoryList();
        foreach (var item in await provider.Category.GetCategoriesAsync()){
            list.Categories.Add(new CategoryResponse{
                Id = item.CategoryId,
                Name = item.CategoryName,
                Description = item.Description,
                ImageUrl = item.ImageUrl 
            });
        } 
        return list;
    }
}

Delare CategoryService in Program.cs

app.MapGrpcService<CategoryService>();

2. Client

Install package

dotnet add package Grpc.Net.Client
dotnet add package Google.Protobuf 
dotnet add package Grpc.Tools
dotnet add package Grpc.Net.ClientFactory

Declare Client

builder.Services.AddGrpcClient<CategoryService.CategoryServiceClient>(p =>{
    p.Address = new Uri(builder.Configuration["GrpcServer:Url"] ?? throw new Exception("Not found GrpcServer:Url"));
});

Repository

Creat class Category with content following:

public class CategoryRepository{
    CategoryService.CategoryServiceClient client;
    public CategoryRepository(CategoryService.CategoryServiceClient client) => this.client = client;
    public async Task<IEnumerable<CategoryResponse>> GetCategoriesAsync(){
        var response = await client.GetCategoriesAsync(new Empty());
        if(response != null) return response.Categories;
        throw new Exception("Not found Category");
    }
}