gpt4 book ai didi

WCF MessageContract 继承

转载 作者:行者123 更新时间:2023-12-04 16:07:16 24 4
gpt4 key购买 nike

我对 WCF 相当陌生,只是有一个关于如何正确使 MessageContract 继承工作的问题。我的设置的简化版本如下 - 一个“基本”消息类型,然后是另一个从它继承的“测试”消息。

[MessageContract]
public abstract class BaseMessage
{ }

[MessageContract]
public class TestMessage : BaseMessage
{ }

然后我在 ServiceContract 上有一个异步 OperationContract 定义为:
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginFindRequest(BaseMessage request, AsyncCallback callback, object asyncState);

我遇到的问题是在调用 BeginFindRequest 方法并传入请求参数的 TestMessage 实例时,WCF 框架正在将 TestMessage 实例反序列化为服务/服务器端的 BaseMessage。由于它被定义为抽象类,因此会导致以下错误:

"The message cannot be deserialized into MessageContract type BaseMessage since it does not have a default (parameterless) constructor."



从我在 MessageContract 继承上可以找到的有限信息来看,它似乎应该可以正常工作。

所以我的问题是 - 为了让它发挥作用,我错过了什么?或者我应该在 ServiceContract 上专门为该类型定义一个单独的 OperationContract - 缺点是我最终可能会得到许多额外的 OperationContracts?

最佳答案

最后,我发现这篇博文一针见血-

Unfortunately the way that contracts are expressed in WCF makes is very easy to forget what their purpose is: to define the messages send to the operation and being sent back from the operation. In reality you have to think “how would I express this data in XML?”. XML doesn’t support inheritance so whatever you put in the contract is going to have to have some way of mapping to XML. The data contracts used to define the messages are simply a .NET typed convenience for generating the XML for the data you want to pass – if you view them any other way you are destined for a world of pain. So think about the data you want to pass, not how it may happen to be represented in your business layer and design your DataContracts accordingly.



http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,a3775eb1-b441-43ad-b9f1-e4aaba404235.aspx

因此,我将重构以提供具有显式契约(Contract)类型的附加方法。这也将允许我通过删除所有类型检查来清理服务实现。

感谢您的帮助。

关于WCF MessageContract 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1321278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com