Archived

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

yaroslavd

SerializationSurrogate Problem in C#

Recommended Posts

yaroslavd    150
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
yaroslavd    150
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
yaroslavd    150
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?

[edited by - yaroslavd on March 23, 2004 9:31:34 PM]

Share this post


Link to post
Share on other sites
eagleone    122
Not that I know of.

If you think about it, it makes perfect sense. Since a class can implement mulitple interfaces - which one should the SurrogateSelector choose if more than one were registured.

Have you tried inheritance instead of an interface pattern?

Share this post


Link to post
Share on other sites
yaroslavd    150
You are right, that makes sense. But I have to have IRecordable as an interface because the recordable classes may have to be derived from some other class. The method I described above seems to work fine.

Share this post


Link to post
Share on other sites