How to extend generated grpc contract class

241 views Asked by At

I use grpc for service interaction. I have MyNamespaceA which is the output folder for grpc generated code. So I create the following .proto file:

syntax = "proto3";

option csharp_namespace = "MyNamespaceA";

message MyClass
{
    int32 myProp1 = 1;
}

Next, in my .csproj

<Protobuf Include="path_to_proto" GrpcServices="Client" />

So the following class is generated in MyNamespaceA:

namespace MyNamespaceA
{
    public sealed partial class MyClass: pb::IMessage<MyClass>
    ...
}

I want to add some more properties to this class. So I create a codefile (physically it is in another folder but I specify the correct namespace in the file itself) with the following contents:

namespace MyNamespaceA
{
    public partial class MyClass
    {
        public string MyProperty { get; set; }
    }
}

Aaand it does not work. When in my service I try to access myClassInstance.MyProperty I get an error

The name 'MyProperty' does not exist in the current context

The same thing is when I try to access MyProp1 from my partial class - it simply does not see if it exists.

What am I doing wrong?

1

There are 1 answers

0
Jon Skeet On BEST ANSWER

The problem was revealed in comments to be that the two partial class declaration were in different projects. For two partial class declarations to "merge", they must:

  • Be in the same project (because only a single actual class is compiled into a single assembly)
  • Be declared in the same namespace
  • Be declared with the same name

There are then requirements around matching modifiers etc, but the compiler will flag if those aren't met... whereas if any of the above three conditions isn't met, the compiler won't even consider that the two declarations are trying to contribute to the same class.