Archived

This topic is now archived and is closed to further replies.

yaroslavd

Using SerializationSurrogate in C#

Recommended Posts

Hi, guys. I have a problem with saving/loading my objects. I have a Recorder class which has static methods for saving/loading objects of type IRecordable. I also have a nested private class SerializationSurrogate : ISerializationSurrogate. Then, static IFormatter Formatter = new BinaryFormatter(). Then, I assign to its SurrogateSelector property a new SurrogateSelector like this:
SurrogateSelector ss = new SurrogateSelector();
ss.AddSurrogate(typeof(IRecordable),Formatter.Context,new SerializationSurrogate());
Formatter.SurrogateSelector = ss;
I checked that the SerializationSurrogate constructor is called. However, its GetObjectData and SetObjectData methods never get called during Serialization. Can anyone help me with this problem? Lemme know if you want the whole source code. Thanks in advance.

Share this post


Link to post
Share on other sites
I figured out what the problem is. However, I dunno how to fix it. Basically, when I pass in an object of Character (which implements IRecordable), it looks for the surrogate with the type Character. It ignores the fact that the object is of type IRecordable, also.

Basically, I want this SerializationSurrogate to handle data of any type that implements IRecordable. How can I do this without making a seperate surrogate for each type?

Thanks in advance.

Share this post


Link to post
Share on other sites
This is how I fixed it:


SurrogateSelector ss = new SurrogateSelector();

foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
if(type.GetInterface("IRecordable")!=null)
ss.AddSurrogate(type,Formatter.Context,new SerializationSurrogate());

Formatter.SurrogateSelector = ss;


Is there a better way?

Share this post


Link to post
Share on other sites