I am building up a runtime model for protobuf-net in runtime using reflection without annotating the classes I need to serialize.
Some of the classes I need to serialize use inheritance and of course I want all the properties from the base class(es).
protobuf-net does not crawl the inheritance tree by default so you need to tell it about base classes. So I wrote a little piece of code to do this:
public class InheritanceTest
{
public static string CreateProto()
{
var model = ProtoBuf.Meta.RuntimeTypeModel.Default;
var type = typeof(SubClass);
if (null != type.BaseType && type.BaseType != typeof(Object))
{
var hierarchy = new List<Type> { type };
var baseType = type.BaseType;
while (null != baseType)
{
if (baseType != typeof(Object))
{
hierarchy.Add(baseType);
}
baseType = baseType.BaseType;
}
hierarchy.Reverse();
var metaType = model.Add(hierarchy.First(), true);
for (int i = 1; i < hierarchy.Count; i++)
{
model.Add(hierarchy[i], true);
metaType = metaType.AddSubType(i, hierarchy[i]);
}
}
else
{
model.Add(type, true);
}
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(p => p.Name);
var tagNumber = 1;
foreach (var propertyInfo in properties)
{
model[type].Add(tagNumber, propertyInfo.Name);
tagNumber++;
}
var schema = model.GetSchema(type, ProtoSyntax.Proto3);
return schema;
}
}
public class BaseClass
{
public string StringPropOnBaseClass { get; set; }
}
public class SubClass : BaseClass
{
public string StringPropOnSubClass { get; set; }
}
That produces a .proto file like this:
syntax = "proto3";
package ProtoBufferSerializerTest;
message BaseClass {
// the following represent sub-types; at most 1 should have a value
optional SubClass SubClass = 1;
}
message SubClass {
string StringPropOnBaseClass = 1;
string StringPropOnSubClass = 2;
}
Why is the BaseClass included in the .proto file? There is no reason why this needs to bleed out into the public wire format.
Is there a way I can tell the runtime model not to include this in the .proto flie?
BR