我正在将我的gRPC应用程序从.net框架移动到.net core。
我有两个主要的proto
文件如下
/Proto/common/common.proto
/Proto/my-service.proto
my-service.proto
导入common.proto
像这样简单:
通用原型
syntax="proto3";
package common;
option csharp_namespace = "Koko.Wawa";
message ValidationFailure {
string property_name = 1;
string error_message = 2;
}
message ValidationResult {
bool is_valid = 1;
repeated ValidationFailure errors = 2;
}
my-service.proto
syntax="proto3";
package google.protobuf;
option csharp_namespace = "Koko.Wawa";
import "common/common.proto"; // << in gRPC .net Core Template it gives error
message CreateDraftPackageRequest {
string package_type = 1;
repeated int32 client_ids = 2;
}
message CreateDraftPackageResponse {
int32 id = 1;
string package_type = 2;
int64 created_on = 3;
int32 package_delivery_status = 4;
common.ValidationResult validation_result = 5;
}
service ExportPackageService {
rpc CreateDraftPackage (CreateDraftPackageRequest) returns (CreateDraftPackageResponse);
}
在Powershell命令中,我使用protoc
命令行生成C#类。此外,我对其进行了修改,使其也适用于.net core。
$exe = "${env:USERPROFILE}.nugetpackagesgrpc.tools2.24.0-pre1toolswindows_x64protoc.exe"
$plugin = "${env:USERPROFILE}.nugetpackagesgrpc.tools2.24.0-pre1toolswindows_x64grpc_csharp_plugin.exe"
& $exe -I .ProtosCommon --csharp_out .OutputCommon .ProtosCommoncommon.proto --grpc_out .OutputCommon --plugin=protoc-gen-grpc=$plugin --csharp_opt=file_extension=.g.cs --grpc_opt=internal_access
& $exe -I .Protos --csharp_out .Output .Protosexport-package-service.proto --grpc_out .Output --plugin=protoc-gen-grpc=$plugin --csharp_opt=file_extension=.g.cs --grpc_opt=internal_access
一切都与这种方法完美配合。但是我试图依赖 .net core 3 中的新 gRPC 模板,您将不断收到一个文件未找到错误!在
import "common/common.proto"; // <<<<<
将import
更改为相对于项目根目录的路径:
import "Proto/Common/common.proto";
如果您仍然想直接使用exe
,请将-I
参数更改为项目 dir,例如.
:
& $exe -I . --csharp_out .Output .Protosexport-package-service.proto --grpc_out .Output --plugin=protoc-gen-grpc=$plugin --csharp_opt=file_extension=.g.cs --grpc_opt=internal_access