In my app I have a lot of XMLs to serialize from, so I have created quite a lot of models, to serialize to. I use System.Xml.Serialization, so it needs parameterless constructor and public access to properties to write deserialized data to.
Now, I want to implement Memento Pattern to provide Undo and Redo functionality, and in that case it would be good to be able to have immutable objects, so there would not be any bug related to that I changed some property instead of creating new instance.
The problem is I don't see any solution that would provide me both solutions at once - being able to deserialize objects and then provide immutability for Memento pattern (well, there is popsicle immutability but I am not sure about it). Creating separate objects (records or so) that my deserialized objects would be converted to after program is done with deserialization seems like solution, but it has a flaw o introducing a lot of new types that consume time and increase upkeep cost later.
Do you guys have other ideas or patterns that I could use?
I was able to create a solution with the help of this article. The only caveat is it requires
DataContractSerializerinstead ofSystem.Xml.Serialization. Here is a dotnetfiddle of my implementation.Update If you must use
System.Xml.Serialization, I recommended using a layered approach to convert between your mutable and immutable models. Here is my dotnetfiddle of this approach.This method is less generic as it will require you to create the mapping logic for each model type. You could simplify that process with something like AutoMapper, but I prefer to do this manually.