WCF 和数据契约接口 [英] WCF and interfaces on data contracts

查看:30
本文介绍了WCF 和数据契约接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 svcutil 创建 WCF 代理时,是否可以包含数据契约继承的接口,例如:

While creating the WCF proxy using svcutil, is it possible to include the interfaces as well from which the data contracts inherit, e.g.:

public class SomeType: ISometype
{
   public string Name { get; set; }
}

public interface ISometype
{
   public string Name { get; set; }
}

当我使用它创建代理时,在客户端创建了 SomeType 类型,但没有创建接口,也没有继承.我尝试将接口标记为 DataContract,但不允许使用该属性.

When I create the proxy using this, the SomeType type is created at the client but the interface isn't created and there is no inheritance either. I tried marking the interface as DataContract but that attribute isnt allowed.

可以做我想做的事吗?

推荐答案

WCF 使用序列化消息传递,所有这些消息都需要能够使用 DataContractSerializer 或 XmlSerializer 进行序列化.而那些在客户端和服务器之间传递的消息需要可以用 XML 模式表达.

WCF uses serialized messaging, and all those messages need to be able to be serialized using a DataContractSerializer or an XmlSerializer. And those messages going between the client and the server needs to be expressible in XML schema.

现在,XML 模式对接口一无所知——它完全是关于具体的、实际的类型.对于常规场景,您的客户端可以是从 .NET 到 PHP 到 Ruby 到(任何)的任何内容,您需要确保以可以用 XML 模式表示的方式表达您想要在客户端和服务器之间发送的所有内容 - 接口不能.所以在通用场景中真的没有办法支持这一点.

Now, XML schema doesn't know anything about interfaces - it's all about concrete, actual types. For a regular scenario where your clients can be anything from .NET to PHP to Ruby to (whatever), you need to make sure to express everything you want to send between client and server in a way that can be represented in XML schema - interfaces cannot. So there's really no way to support this in a general purpose scenario.

如果您控制电线的两端,例如您编写客户端和服务器,并且都在 .NET 中,然后您可以这样做:

If you're controlling both ends of the wire, e.g. you write both the client and the server, and both in .NET, then you can do this:

  • 将您的 DataContracts(以及您的 ServiceContracts、OperationContracts 和 FaultContracts)全部放入一个单独的 MyServiceContracts 程序集

从您的服务端代码和客户端引用该程序集.在这种情况下,当您准备创建客户端代理时,您提到的那些类型已经存在,WCF 将很乐意重用该程序集中的这些类型.由于这是您引用的 .NET 程序集,因此您可以在其中包含 .NET 支持的任何内容 - 包括接口.

reference that assembly from both your service-side code, as well as the client. In that case, when you go about to create the client proxy, those types you mention are already present and WCF will happily reuse those types from that assembly. And since that's a .NET assembly you're referencing, you can have anything in there that .NET supports - including interfaces.

这篇关于WCF 和数据契约接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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