Wcf、序列化、只读成员
我正在学习 WCF,今天面临的挑战之一是实现此设计:
[DataContract]
public class MyOwnFaultException : FaultException<MyResult>
{
public MyOwnFaultException(MyResult result) : base(result) {}
}
[DataContract]
public class MyResult
{
readonly DefinedResults dres;
public MyResult(DefinedResults res) {
dres = res;
}
[DataMember]
public DefinedResults DRes
{
get { return this.dres; }
//do not want to have the setter for this, but w.o it .net throws exception
}
}
[DataContract]
public enum DefinedResults
{
Success = 0,
Fail = 1,
}
服务
[OperationContract]
[FaultContract(typeof(MyOwnFaultException))]
void TestRemoteException();
因此,当我尝试创建对“错误”服务的引用时,我自然会得到“No Set”对于“DRes 成员”,这是可以理解的例外情况。但是如何对用于结果指示器的值对象实现只读字段模式?
I am learning WCF and one of the challenges I am faced with today is to implement this design:
[DataContract]
public class MyOwnFaultException : FaultException<MyResult>
{
public MyOwnFaultException(MyResult result) : base(result) {}
}
[DataContract]
public class MyResult
{
readonly DefinedResults dres;
public MyResult(DefinedResults res) {
dres = res;
}
[DataMember]
public DefinedResults DRes
{
get { return this.dres; }
//do not want to have the setter for this, but w.o it .net throws exception
}
}
[DataContract]
public enum DefinedResults
{
Success = 0,
Fail = 1,
}
Service
[OperationContract]
[FaultContract(typeof(MyOwnFaultException))]
void TestRemoteException();
So, naturally when I try to create a reference to my 'faulty' service I get the "No Set For DRes member" exception which is understood. But how to I implement the readonly field pattern to the value object used for result indicator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为服务共享模式和契约,而不是类。
话虽如此,你可以通过以下方式破解它:
This is because services share schema and contract, not class.
Having said that, you could hack it by doing:
使用WCF时没有值对象。通过操作接收和发送的所有对象都必须是可序列化的 - 必须具有无参数构造函数(正如注释中所指出的,这对于 DataContractSerializer 来说不是必需的),并且所有序列化字段都必须是可写的。如果您想发送不可序列化的对象,您可以实现 IDataContractSurrogate 或只是实现您自己的数据传输对象 (DTO)。
There is no value object when using WCF. All object received and send by operation must be serializable - must have parameterless constructor (as marc pointed in comment this is not necessary for
DataContractSerializer
) and all serialized field must be writable. If you want to send object which is not serializable you can implement IDataContractSurrogate or just implement your own Data transfer object (DTO).