简体   繁体   中英

protobuf-net - Not specify sub types of a base class

I have an inheritance chain such as this:

[ProtoContract]
public abstract class Message
{
    [ProtoMember(1, OverwriteList = true)]
    public List<Header> Headers {get; set;}
}

[ProtoContract]
public class EventMessage<T> : Message
{
    [ProtoMember(2)]
    public T Event {get; set;}
}

The inheritance chain is very straight forward (my . In order to get the Headers to be included in the serialization, I need to do:

RuntimeTypeModel.Default[typeof(Packet)].AddSubType(3, typeof(Message<PayloadType>));

I know this sort of answer (the line above) has been documented on quite a few StackOverflow posts. However, I don't like this design because then I need to declare all my subtypes ahead of time and it's also implying a limited, small number of subtypes.

I'm attempting to code a message bus in my application, using protobuf-net for the serialization/deserialization. The message bus needs to send out 'events' and respond to request/replies. Since I have many (easily > 100) events in my system, I don't want to declare a subtype for every closed generic type in the RuntimeTypeModel.

Does protobuf-net have the ability to infer subtypes/classes? Or ideally, I'd like something like:

RuntimeTypeModel.Default[typeof(Packet)].AddSubType(3, typeof(Message<>));

(Which I tried and it doesn't work).

In the protobuf wire format, the only identifiers sent are the numeric keys (like the 1,2,3 in your example). After that data has been serialized, you will presumably want it to deserialize in the future - and doing that reliably if the keys are not explicitly specified is hugely problematic. Especially since those sub-types could be declared in different assemblies, so it can't even infer them by reflection.

At the moment, the short answer is "they must be specified". Note that I didn't say "in attributes" - the subtypes can also be specified via the RuntimeTypeModel API at runtime, if that is more convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM