I am creating an gRPC service and we decided to choose the code first approach with protobuf-net. Now I am running into a scenario where we have a couple of classes that need to be wrapped. We do not want to define KnownTypes in the MyMessage class (just a sample name to illustrate the problem). So I am trying to use the Any type which currently gives me some struggle with packing.
The sample code has the MyMessage which defines some header values and has to possiblity to deliver any type as payload.
[ProtoContract]
public class MyMessage
{
[ProtoMember(1)] public int HeaderValue1 { get; set; }
[ProtoMember(2)] public string HeaderValue2 { get; set; }
[ProtoMember(3)] public Google.Protobuf.WellknownTypes.Any Payload { get; set; }
}
[ProtoContract]
public class Payload1
{
[ProtoMember(1)] public bool Data1 { get; set; }
[ProtoMember(2)] public string Data2 { get; set; }
}
[ProtoContract]
public class Payload2
{
[ProtoMember(1)] public string Data1 { get; set; }
[ProtoMember(2)] public string Data2 { get; set; }
}
Somewhere in the code I construct my message with a payload ...
Payload2 payload = new Payload2 {
Data1 = "abc",
Data2 = "def"
};
MyMessage msg = new MyMessage
{
HeaderValue1 = 123,
HeaderValue2 = "iAmHeaderValue2",
Payload = Google.Protobuf.WellknownTypes.Any.Pack(payload)
};
Which doesn't work because Payload1
and Payload2
need to implement Google.Protobuf.IMessage
.
Since I can't figure out how and do not find a lot information how to do it at all I am wondering if I am going a wrong path.
- How is it intedend to use Any in protobuf-net?
- Is there a simple (yet compatible) way to pack a C# code first class into Google.Protobuf.WellknownTypes.Any?
- Do I really need to implement Google.Protobuf.IMessage?
My Any implementation.
'System.Object' can be used as a field or property in a surrounding Container record:
Serialization