WCF序列化和不变量的问题 [英] Problems with WCF serialization and invariants

查看:79
本文介绍了WCF序列化和不变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。


我在WCF服务使用的类中添加了几个不变量(这意味着当它传递回到WCF服务时会被序列化)客户)。现在,问题是当反序列化obejct时,不会调用我为执行所需的初始化而添加的(自定义)默认构造函数。但是,可以在方法上使用OnDeserializingAttribute来确保正确初始化对象。一切都运行正常,直到你有一个以上的不变量。


例如,假设你有2个属性,A和B,并且每个属性都有一个不变量(简单的就是这样;例如,假设它们不能为空)。在使用OnDeserializing属性注释的方法中,您结束调用new并设置每个属性。这是有问题的,因为每当你设置一个属性(比如A)时,你最终会调用代码契约的不变方法,因为我只设置了第一个属性,我最终会得到一个异常因为B为null并且打破不变量。


未来代码合约能否与WCF和序列化很好地合作?


谢谢


Luis Abreu

解决方案

您好Luis,


而不是使用 OnDeserializingAttribute ,尝试实施 ISerializable 并提供反序列化构造函数。


Custom Serialization,§实现ISerializable接口
http://msdn.microsoft.com/en-us/library/ty01x675.aspx

- 戴夫


Hello guys.

I've added a couple of invariants to a class which is used by a WCF service (meaning that it gets serialized when it's passed back to the client). Now, the problem is that the (custom) default constructor I've added to perform the required initializations isn't called when an obejct is deserialized. However, one can use the OnDeserializingAttribute on a method for ensuring that the object is correctly initialized. Everything runs fine until youy have more than one invariant.

For instance, suppose you've got 2 properties, A and B, and an invariant for each (simple one will do; for instance, suppose they can't be null). From within the method which is annotated with the OnDeserializing attribute, you end calling new and setting each property. This is problematic because whenever you set a property (say, A), you'll end up calling the code contract's invariant method and since I've only set the 1st property, I'll end up getting an exception because B is null and breaks the invariant.

Will code contracts play nicely with WCF and serialization in the future?

thanks


Luis Abreu

解决方案

Hi Luis,

Instead of using OnDeserializingAttribute, try implementing ISerializable and providing a deserialization constructor instead.

Custom Serialization, §Implementing the ISerializable Interface
http://msdn.microsoft.com/en-us/library/ty01x675.aspx

- Dave


这篇关于WCF序列化和不变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆