I am using the BinaryFormatter to serialize an object graph, and when there are multiple references to the same object, I want this to be preserved after deserialization, i.e. the references in the deserialized data should still refer to the same object.
This seems to work for all objects that are part of the same Deserialize() call, but not for separate calls on the same BinaryFormatter instance. Is there a way to configure it differently, so that it will preserve references correctly over multiple calls?
See the following example, where ReferenceEquals() with objects from different Deserialize() calls returns false.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializeTest
{
[Serializable]
class Data
{
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = new Data { Value = 1234 };
using (var fs = new FileStream("serialized.dat", FileMode.Create, FileAccess.Write))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, (data, data));
formatter.Serialize(fs, data);
}
using (var fs = new FileStream("serialized.dat", FileMode.Open, FileAccess.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
var (data1, data2) = ((Data, Data))formatter.Deserialize(fs);
var data3 = (Data)formatter.Deserialize(fs);
// object references from separate calls are not the same?
// accordings to docs, same Formatter and ObjectIdGenerator should lead to the same object being deserialized.
Debug.Assert(ReferenceEquals(data1, data2), "objects from same call");
Debug.Assert(ReferenceEquals(data1, data3), "objects from different calls");
}
}
}
}