I am trying to serialize/deserialize objects that have factory-created members. For example, lets say there are a member of type Foo, which is instantiated using FooFactory.CreateFoo(int bar).
My current idea is to
1.create a custom XmlReader (for example, derive from XmlTextReader), and attach the factory to it
2.implement IXmlSerializable
3.in ReadXml(), I can the grab the factory from the reader.
Not sure if this is the most elegant way to do it, has anybody made similar attempts ?
XmlSerializersimply isn’t set up for that. I would strongly suggest that if you want to useXmlSerializer, your best bet would be to map your data to a simpler DTO model first, and serialize that. When writing code back from the DTO to your model, add the factory creation there, in regular code. The DTO model should be simple; simple enough forXmlSerializerto be happy with it.Yes, implementing
IXmlSerializableis an option, however: that API is very hard to get 100% right (to handle all the various ways xml can appear to it). I find that API very hard, and I do a lot of serialization. I humbly submit that writing a few lines of code to map from your main model to a DTO model is a lot more robust (and a lot quicker) than trying to implementIXmlSerializable.For example, you could have:
then you can convert from
FootoFooDTOsimply by: