开发者

XML-Serialization and the need public properties

in my Silverlight 4 application, I save my object via DataContractSerializer XML-Serialization - which is quite easy:

public byte[] SerializeModel(ServiceModel model)
{
    System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(ServiceModel));
    System.IO.MemoryStream ms = new System.IO.MemoryStream();

    serializer.WriteObject(ms, model);

    byte[] bytes = ms.ToArray();
    ms.Close();

    return bytes;
}

... and loading them easily via:

public ServiceModel DeserializeModel(string stream)
{
    System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(ServiceModel));
    System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(stream));

 开发者_如何学Python   object result = serializer.ReadObject(reader);

    return (ServiceModel)result;
}

(Error Handling ommited)

The problem for me is, that I need to make the data to be saved (or better: to be loaded) public properties with getter and setter. That leads to a loss of control over data integrity. I.e. I have a collection of objects and I want to control what objects are to be added or removed. I would need to subclass or re-implement the collection, changing Add and Remove methods and whatever else method I'd need to control. But making it private keeps me from using the DataContractSerializer.

Any suggestions how to keep it simple but keeps the control over the objects within the class?

Thanks in advance,

Frank


Typically what I do in these situations is to keep my serialization objects as POCOs (just gets/sets) and then once i deserialize them I will do whatever additional checks i need to make and throw/error handle as appropriate.

So this means I have my "interface" for serialization which is just the POCO, and then once I deserialize it I do any consistency checks and load/adapt into my entities. Where I work we do this with our web services, where we have our domain entities and our interface classes. Once we get the request we adapt it to our business entities and then pass it into the business layer and reverse the process for results.

I kind of see serialization as crossing a layer and thus all input should be validated and then adapted to keep coupling at a minimum.

But that's just my $0.02

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜