Bekjan Juma
Bekjan Juma

Reputation: 563

Importing proto files from different directories

I'm struggling writing the right configuration for grpc imports.

So the .net solution structure is like:
\Protos\Common\common.proto
\Protos\Vehicle\car.proto
\CarMicroservice

Inside car.proto I have: import "common.proto"

What I want is the generated grpc code to be inside the project CarMicroservice.
Inside CarMicroservice.csproj I have written the path to the protos:

<Protobuf Include="common.proto" ProtoRoot="..\Protos\Common\" />
<Protobuf Include="car.proto" ProtoRoot="..\Protos\Vehicle\" />

But getting error: 'common.proto' no such file or directory

The question is: How do I correctly import common.proto inside the car.proto?

Note: I already looked at the similar issue, but couldn't make it work for my case
Importing .proto files from another project

Upvotes: 9

Views: 12171

Answers (2)

Arshia001
Arshia001

Reputation: 1872

Alternatively, there are two other ways to specify include directories for protoc.

First, there is a global property named Protobuf_AdditionalImportsPath. If you specify this property in your .csproj/.fsproj, it will be passed on to protoc for every .proto in that project. You can use it like this:

<PropertyGroup>
    <Protobuf_AdditionalImportsPath>../../my/other/directory</Protobuf_AdditionalImportsPath>
</PropertyGroup>

There is also a AdditionalImportDirs property you can specify directly on <Protobuf> elements. This will likely only be valid for the .protos you specify it on:

<Protobuf Include="MyProto.proto" Link="MyProto.proto" AdditionalImportDirs="../../my/other/directory" />

Keep in mind that in both cases, you can specify any directory you want, regardless of whether it is a parent of the .proto you're compiling.

Also keep in mind that the import path you specify in your .proto needs be relative to one of the import directories you specify.

Upvotes: 5

Bekjan Juma
Bekjan Juma

Reputation: 563

Ok, I finally solved the issue. Also @DazWilkin pointed it out.

  1. You can't use relative paths in the import, so you should use absolute path of the project. In my case it was: import "Common/common.proto"
  2. Use the project root for the location of proto files. So instead of ProtoRoot="..\Protos\Common\" use ProtoRoot="../Protos/"
    Now comes the interesting part.
    For some reason when I used backslashes for the ProtoRoot path as "..\Protos\
    I was getting errors as 'file not found'. So don't use the backslashes for paths. The final code in CarMicroservice.csproj is like the following:
<Protobuf Include="Common/common.proto" ProtoRoot="../Protos/" />
<Protobuf Include="Vehicle/car.proto" ProtoRoot="../Protos/" />

Upvotes: 13

Related Questions