Search⌘ K
AI Features

Using Code-First gRPC on .NET

Discover how to use the code-first approach to create gRPC services in ASP.NET Core with C#. Learn to define service contracts and messages using annotations, implement the service and client, and streamline development by automatically generating gRPC components without manually writing Protobuf files.

The standard way of writing gRPC services is to manually write Protobuf files and then write their implementation in code. The main disadvantage of this process is that it's time-consuming. However, there's a way to write gRPC services without manually writing Protobuf definitions. It's called the code-first approach.

When we apply the code-first approach, all of our code is written in C#. We need to apply appropriate annotations to our classes. All the necessary gRPC components will be automatically generated for us once we compile our application. To learn how to use this approach, we'll apply some changes to the following setup.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Grpc.Net.Client" Version="2.48.0" />
    <PackageReference Include="protobuf-net.Grpc" Version="1.0.179" />
  </ItemGroup>

</Project>
Initial setup

Adding the code-first gRPC contract

To start using code-first gRPC, we first need to add some NuGet libraries. We've done so to both of the project files. In the ...