Create Service Using RestAPI and gRPC [Dotnet6]

Macus.y
3 min readSep 12, 2022

--

บทความนี้จะมาแนะนำการ สร้าง Service โดยใช้ทั้ง RestApi และ gRPC
โดยจะออกแบบ ระบบตามรูปด้านล่าง เผื่อมีความต้องการที่จะ delivery ทั้งสอง
แบบให้ user ใช้งาน 👋👋

source code : https://github.com/pichayean/samplecatservice.git

เตรียมโปรเจค 😇

✔ Create Sample Cat Service
— dotnet new classlib -o samplecatservice

✔ Create Sample Cat Service Api
— dotnet new webapi -o samplecatservice.api

✔ Create Sample Cat Service gRPC
— dotnet new grpc -o samplecatservice.grpc

✔ Create Sample Cat Service Client
— dotnet new console -o samplecatservice.client

  1. Sample Cat Service 👩🏻‍💻

สร้าง File ตามรูปด้านบน
AppSettings.cs =>
CatEntity.cs => Entity file
CatLogics.cs => Logic process for cat service
ICatLogics.cs => Interface of Logic process for cat service
CatRepository.cs => Repository
IRepository.cs => Interface of Repository
CatModuleExtension.cs => ExtensionMethod for DI Service

2. Sample Cat Service Api 👩🏻‍💻

สร้าง File ตามรูปด้านบน
CatsController.cs => Controller file
Cat.Response.cs => Response file
CreateCat.Request.cs => Request file
CreateCat.Response.cs => Response file
Error.Response.cs => Response file
Success.Response.cs => Response file
UpdateCat.Request.cs => Request file
Dockerfile

[Edit]Program.cs => Register Cat Module

[Additional] samplecatservice.api.csproj
<ProjectReference Include=”..\samplecatservice\samplecatservice.csproj” />

3. Sample Cat Service gRPC 👩🏻‍💻

สร้าง File ตามรูปด้านบน
cats.proto => proto file
CatsService.cs => CatsService file
Dockerfile

[Edit]Program.cs => Register Cat Module and Register CatsService

[Additional] samplecatservice.grpc.csproj
<ProjectReference Include=”..\samplecatservice\samplecatservice.csproj” />

4. Sample Cat Service Client 👩🏻‍💻
เพื่อใช้ทดลองเรียกใช้งาน gRPC Service

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

สร้าง File ตามรูปด้านบน
CatGrpcClient.cs
CatHttpClient.cs

[Additional] samplecatservice.client.csproj
<Protobuf Include=”Protos\cats.proto” GrpcServices=”Server” />

5. docker-compose 😁

docker-compose up -d
dotnet run — project samplecatservice.client
Project client เเสดงให้เห็นการเรียกใช้งาน ทั้ง RestApi และ gRpc service

👍👍👍

คุณสามารถดูรายละเอียด เพิ่มเติมได้ กด => 📋 ≤= เลยนะครับ
มีคำถามหรือส่วนไหนที่ไม่ถูกต้องก็ขออภัยด้วยนะครับ

Ref: https://docs.microsoft.com/en-us/aspnet/core/tutorials/grpc/grpc-start

--

--

Macus.y
Macus.y

Written by Macus.y

“Many of life’s failures are people who did not realize how close they were to success when they gave up.”– Thomas A. Edison 😇😇😇

No responses yet