How can one do reference fixup (post-processing) using the C# serialization framework?
I have an object graph with objects referencing other objects. They all implement the ISerializable
interface and they all have instance ID's, so representing the references in the serialized state is easy.
The krux is that when the deserialization constructor is called, all objects being referenced by that object might not have been deserialized, so the references can't be set to valid objects. And I can't find any way to hook into a post-processing step in the C# serialization framework to do the reference fixup. Is there a way to do it?
As per request, here is a contrived class that I think highlights the problem.
[Serializable]
public class Pony : ISerializable
{
public int Id { get; set; }
public string Name { get; set; }
public Pony BFF { get; set; }
public Pony() {}
private Pony(SerializationInfo info, StreamingContext context) {
Id = info.GetInt32("id");
Name = info.GetString("name");
var bffId = info.GetInt32("BFFId");
BFF = null; // <===== Fixup! Find Pony instance with id == bffId
}
public void GetObjectData(SerializationInfo info, StreamingContext ontext) {
info.AddValue("id", Id);
info.AddValue("name", Name);
info.AddValue("BFFId", BFF.Id);
}
}
And here is the (de)serialization code:
var rd = new Pony { Id = 1, Name = "Rainbow Dash" };
var fs = new Pony { Id = 2, Name = "Fluttershy", BFF = rd };
rd.BFF = fs;
var ponies = new List<Pony>{ rd, fs };
Stream stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, ponies);
stream.Seek(0, SeekOrigin.Begin);
var deserializedPonies = (List<Pony>)formatter.Deserialize(stream);
This question doesn't solve my problem: .net XML Serialization - Storing Reference instead of Object Copy
I would like to use the BinaryFormatter + ISerializable framework for the serialization and not switch to XmlFormater.