views:

329

answers:

2

We have a rather large object graph that needs to be serialized and deserialized in a lot of different ways (modes). In some modes we want certain properties to be deserialized and in some we don't. In future modes it might also be possible that there are more options for properties than yes or no. The problem is now how we implement these modes.

Apporach A (use deseriliazation constructor and ISerializable.GetObjectData):

If we let each object of the graph serialize itself using a deserialization constructor we get a lot switches for all the different modes of deserialization. The advantage of this approach however is that all the deserialization logic is at one location and if we add new properties we just need to modify the ISerializable.GetObjectData and the deserialization constructor. Another advantage is that the object might take internal states into account that might be exposed publically. The most important disadvantage is that we dataobject itself needs to know about all possible serialization modes. If we need a new mode we need to modify the dataobjects.

Apporach B (Deserialization Factory Classes/Methods ):

Another approach would be to have some sort Deserialization Factory Classes/Methods one for each mode that does the serialization and deserialization externally (e.g. GraphSerializer.SerializeObjectTypeX(ObjectTypeX objectToSerialze). The advantage here is that whenever we want a new mode we just add a new Factory Class/Method and our Dataobject do not get cluttered with all the serialization modes that get introduced. The main disadvantage here is that I would have to write the same serialization code over and over for all the different modes. If two modes differ just in one or two properties but I would have to implement the complete logic for the whole graph again. When I add a new property to a dataobject I need to update all the factory classes.

So I wonder if there is a better approach to this IMHO general problem. Or even a best practise in .NET? Or maybe I am just approaching the whole thing from a wrong perspective?

A: 

@ aku

Why did you delete you answer? Your approach with NetDataContractSerializer and OnDeserializingAttribute looked interesting. Unfotuantely I did not read everything before you deleted it.

bitbonk
+2  A: 

Make separate serializer classes (a-la XmlSerializer) for each mode, inherit or incapsulate to avoid duplication. Use attributes on properties to mark whether and how they should be serialised in specific mode

ima