I am getting the following error message when trying to serialize my object graph:
Possible recursion detected (offset: 4 level(s)): TestProtobufSerialization.Program+SI
My model looks like this:
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, AsReferenceDefault = true)]
[ProtoInclude(101, typeof(ST))]
[ProtoInclude(102, typeof(SI))]
public class Base
{
public string CreateBy { get; set; }
public string ModifiedBy { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, AsReferenceDefault = true)]
public class ST : Base
{
public string Id { get; set; }
public List<SI> Indexes { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, AsReferenceDefault = true)]
public class SI : Base
{
public string Id { get; set; }
public ST ST { get; set; }
}
The actual code to serialize is the following:
var st = new ST() { Id = "ST001" };
var si = new SI() { Id = "SI001" };
st.Indexes = new List<SI>();
st.Indexes.Add(si);
si.ST = st;
ST newST = serializeDeserializeWithProto<ST>(st, "testing_cyclic_references");
Debug.Assert(st != null, "ST is null!");
and the helper method is:
private static T serializeDeserializeWithProto<T>(T input, string fileName)
{
using (var file = File.Create(fileName + ".bin"))
{
Serializer.Serialize(file, input);
}
T output;
using (var file = File.OpenRead(fileName + ".bin"))
{
output = Serializer.Deserialize<T>(file);
}
string proto = Serializer.GetProto<T>();
File.WriteAllText(typeof(T).ToString() + "_proto.txt", proto, Encoding.ASCII);
Console.WriteLine(proto);
return output;
}
When I am trying to run this code I get the above mentioned exception. The interesting thing is that if I remove the Base class from the ST and SI classes the serialization works. I would like to understand why the serialization works without the Base class and it does not work with the Base class being the parent of ST and SI.
I also created a gist for my repro code.