Context value is null in ISerializationSurrogate

I have an implementation of ISerializationSurrogate to which I want to transfer some data. According to the MSDN article (http://msdn.microsoft.com/en-us/library/h58hxyt6.aspx) you can pass an arbitrary value to a StreamingContext, which will then be available in ISerializationSurrogate.

public class IndexedSurrogate<T> : ISerializationSurrogate {
    public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context) {
        Console.WriteLine(context.Context == null); // <- this is always true
    }
}

I set a context like this

var surrogateSelector = new SurrogateSelector();
var context = new StreamingContext(StreamingContextStates.All, "my arbitrary data");
surrogateSelector.AddSurrogate(typeof(Transform), context, new IndexedSurrogate<Transform>());

BinaryFormatter formatter = new BinaryFormatter();
formatter.SurrogateSelector = surrogateSelector;
formatter.Serialize(stream, list);

The data that I initialize the StreamingContext, in this example, the string "my arbitrary data" never comes into my IndexedSurrogate class, although the GetObjectData method of my IndexedSurrogate class is called. I am completely shocked by this, and the search on the Internet did not find anything, it seems that no one is using an additional parameter in the StreamingContext (or at least no one is talking about this). Any ideas?

+3

Source: https://habr.com/ru/post/1773315/


All Articles