Sharing one gRPC proto file for all solutions

Viewed 2209

I've recently got my hands on gRPC on .net core and so far I'm very pleased with it..

the only problem I have is the proto files, for example: If I make a change on MyProtos.proto file in my grpc server solution. i'll have to update MyProtos.proto files in all my client solutions..

so I was wondering if there are ways of sharing the proto files..

I've tried creating a separate solution and placing the proto files there then reference it to all other solutions but couldn't make it work.

2 Answers

You can distribute proto files with nuget package. Use .nuspec file to pack the files. For example if you *.proto files are under proto folder My.Server.Proto.nuspec can look like this:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
  <metadata>
    <id>My.Server.Proto</id>
    <version>1.0.0</version>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>My Server Proto Files</description>
    <authors>My Company Ltd.</authors>
  </metadata>
  <files>
    <file src="proto/**/*.proto" />
  </files>
</package>

Then in the project where you want to consume the files install grpc dependencies

<ItemGroup>
  <PackageReference Include="Google.Protobuf" Version="3.14.0" />
  <PackageReference Include="Grpc.Tools" Version="2.34.0">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
  </PackageReference>
</ItemGroup>

Install your proto package:

<ItemGroup>
  <PackageReference Include="My.Server.Proto" Version="1.0.0" GeneratePathProperty="true" />
</ItemGroup>

Note the GeneratePathProperty="true". This will allow you to refer to nuget install folder. Now add Protobuf items

<ItemGroup>
  <Protobuf Include="$(PkgMy_Server_Proto)/proto/**/*.proto" ProtoRoot="$(PkgMy_Server_Proto)" GrpcServices="Client" />
</ItemGroup>

The $(PkgMy_Server_Proto) variable will be resolved to My.Server.Proto nuget folder. The variable name starts with Pkg and followed by package name when . replaced by _.

Using Connected Services can easily configure the proto reference of other projects, and you can delete the link in the project file. However, this can only refer to the proto of the local file, not the proto of the project. Of course, there is nothing for the relative path of the same solution the difference You can also quote directly like this, the two have the same effect

<ItemGroup>
  <Protobuf Include="..\Shared\Protos\greet.proto" GrpcServices="Server"/>
</ItemGroup>
Related