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?
Firstly, since you say "where we have a couple of classes that need to be wrapped" (emphasis mine), I wonder if what you actually want here is
oneofrather thanAny. protobuf-net has support for theoneofconcept, although it isn't obvious from a code-first perspective. But imagine we had (in a contract-first sense):This would be implemented (via the protobuf-net schema tools) as:
optionally with an enum to help:
This approach may be easier and preferable to
Any.On
Any:Short version: protobuf-net has not, to date, had any particular request to implement
Any. It probably isn't a huge amount of work - simply: it hasn't yet happened. It looks like you're referencing both protobuf-net and the Google libs here, and using the Google implementation ofAny. That's fine, but protobuf-net isn't going to use it at all - it doesn't know about the Google APIs in this context, so: implementingIMessagewon't actually help you.I'd be more than happy to look at
Anywith you, from the protobuf-net side. Ultimately, time/availability is always the limiting factor, so I prioritise features that are seeing demand. I think you may actually be the first person asking me aboutAnyin protobuf-net.