For our Silverlight Project (SL4) I'm using a Model which might contain Lists (IList<AnotherModel>
). According to good practice and rule CA2227:CollectionPropertiesShouldBeReadOnly
the IList
properties don't have a public setter. We serialize the Model using the DataContractSerializer which is working. But when I try to deserialize, a SecurityException is thrown by DataContractSerializer's ReadObject(Stream)
Method, complaining that the target property (pointing to the IList
property) cannot be set due to a missing public setter.
Since the DataContractSerializer
is sealed and neither extendable nor flexible so I currently see no chance to add some kind of additional rules which allow to deserialize the ILists
using a foreach-loop on Add()
method or some other method of transferring the collection items.
I've also tried to dig into DataContractSerializer
source (using Reflector) to create a little fork but it looks like i'd have to dig very deep and replicating whole serialization classes doesn't seem to be a viable solution.
Do you see another chance to serialize a List with no public setter using the DataContractSerializer
?
Thank you very much in advance for your ideas!
UPDATE
Solved using XmlSerializer.
Thomas
In our case, we found out that we were not strictly bound to the DataContractSerializer
, and interestingly, the XmlSerializer
DOES support serialization of read-only ILists! In fact, it even doesn't allow a public setter for the IList interface in this case (cannot deserialize interface property) but (de-)serializing the ILists items works like a charm.
Only change for us was adding [XmlInclude]
attributes in addition to [KnownType]
(and of course, replacing the few lines from DataContractSerializer.WriteObject(...)
to XmlSerializer.Serialize(...)
.
Thanks for your support! =)