如何使代码契约与数据契约的反序列化一起工作?
我已经为数据协定类编写了一个ContractInvariantMethod,并且在客户端一切正常,但是当这种类型的对象发送到我的服务并且数据协定反序列化器尝试反序列化它时,代码契约检查会妨碍并抛出ContractException,表示不变失败。 原因是在类的(默认)构造函数中,我设置了属性以满足不变量,但显然在反序列化对象时不会调用构造函数。 有解决办法吗?
这是我的数据合约类:
[DataContract]
public class DataContractClass
{
public DataContractClass()
{
this.Field1= this.Field2= -1;
}
[DataMember]
public int Field1 {get; set;}
[DataMember]
public int Field2 {get; set;}
[ContractInvariantMethod]
private void Invariants()
{
Contract.Invariant(this.Field1== -1 || this.Field2== -1);
}
}
I have written a ContractInvariantMethod
for a data contract class, and everything works great on the client side, however when an object of this type is sent to my service, and the Data Contract Deserializer tries to deserialize it, code contract checking gets in the way and throws ContractException
, saying invariant failed.
The reason is that in the (default) constructor of the class, i set the properties to satisfy the invariant, but apparently the constructor doesn't get called when the object is being deserialized.
is there a solution to this?
here is my data contract class:
[DataContract]
public class DataContractClass
{
public DataContractClass()
{
this.Field1= this.Field2= -1;
}
[DataMember]
public int Field1 {get; set;}
[DataMember]
public int Field2 {get; set;}
[ContractInvariantMethod]
private void Invariants()
{
Contract.Invariant(this.Field1== -1 || this.Field2== -1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在运行时检查期间,不变量是
在每个公共方法的末尾进行检查。
因此,当序列化器将 Property1 和 Property2 设置为非 -1 时,您会收到一个契约异常,因为反序列化器不使用构造函数。
所以用这个:
During runtime checking, invariants are
checked at the end of each public method.
So when the Serializer set Property1 and Property2 not to -1 you get a contract exception because the deserializer dont use the constructor.
So use this: