chrism
chrism

Reputation: 561

Serialisation with inheritance in protobuf-net

Given a .proto that looks like this:

message Base {
    string Dummy = 1
}

message Derived {
    Base Super = 1
    string Parp = 2 
}

... And some C# something like:

public class Base {
    public string Dummy;
}

public class Derived : Base {
    public string Parp
}

How would one go about customising the serialisation in protobuf-net to be able to do this? Initially I started looking at using a TypeModel and calling AddSubType for the Base MetaType, but then it seems it creates type definitions for Base with optional fields of all the derived classes (ie the other way around vs what I require)

I thought I might be able to walk the hierarchy myself but looking at TypeModel, it seems to support supplying the type to Deserialise but it uses value.GetType() during serialisation. Even then it wasn't entirely clear how I might do this. Is my only option to use ProtoWriter to write every field by hand? This is what I am currently attempting, but I hoped there was an easier way.

Upvotes: 3

Views: 629

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063864

The first thing to note is that protobuf itself does not support inheritance. There is no "official" layout for this. Protobuf-net will not support serialization the way you desire: the choice of sub-type encapsulation (rather than base-type encapsulation) was made to fix several issues, including:

  • satisfying the Liskov substitution principle
  • working correctly when the serialized type was not known/expected by the caller
  • basically, working at all (for anything other than the simplest example where both ends know in advance exactly which sub-type they are getting, which largely defeats the point of polymorphism)

However, you could map the DTO manually, basically so your DTO layer doesn't use inheritance at all.

Upvotes: 2

Related Questions