在 WCF 服务和客户端之间共享类型






2.57/5 (5投票s)
2007年7月16日
1分钟阅读

69296

425
一篇关于在 WCF 服务和客户端之间共享类型 的文章。
引言
WCF 中一个我发现非常有价值的选项是能够在服务和客户端代理之间共享类型。SvcUtil 的 /reference 选项允许生成的客户端代理重用在共享程序集中定义的某些类型。
背景
当为 Web 服务生成客户端代理时,也会生成所有复杂类型的定义。这会产生两个问题:
- 如果您在多个服务中使用相同的类型,则生成的客户端代码可能对相同的类型有多个定义。
- 服务器类型定义中使用的任何有用的属性、构造函数和集合都会丢失。
虽然第二个问题只是一个麻烦,但第一个问题可能会造成很多头痛。
假设 SharedType
类是在服务使用的代码中这样定义的:
[DataContract(Namespace = "http://mycode.com/types")]
public class SharedType
{
private string name;
[DataMember]
public string Name
{
get { return name; }
set
{
if (value == null || value.Length < 3)
throw new ApplicationException();
name = value;
}
}
[DataMember(Name = "Attributes")]
private List<string> attributes = new List<string>();
public ICollection<string> Attributes
{
get { return attributes; }
}
public SharedType()
{
}
public SharedType(string name)
{
this.Name = name;
}
}
如果客户端代理是在不引用包含数据类型的程序集的情况下生成的,则 SharedType
类将这样生成:
[System.CodeDom.Compiler.GeneratedCodeAttribute
("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute
(Namespace="http://mycode.com/types")]
public partial class SharedType : object,
System.Runtime.Serialization.IExtensibleDataObject
{
private System.Runtime.Serialization.ExtensionDataObject
extensionDataField;
private string[] AttributesField;
private string NameField;
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{
get { return this.extensionDataField; }
set { this.extensionDataField = value; }
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string[] Attributes
{
get { return this.AttributesField; }
set { this.AttributesField = value; }
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get { return this.NameField; }
set { this.NameField = value; }
}
}
很容易注意到,该类型没有带参数 name
的构造函数,并且 Attributes
属性实现为 Array
而不是 List
。
要生成引用原始类型的客户端代理,请使用 ServiceModel
元数据实用工具 (Svcutil.exe) 的以下选项:
"c:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\SvcUtil"
/l:cs
/out:SharedTypeService.cs
/config:..\App.config
/n:*,MyClient.Proxy
<b>/r:..\..\MyTypes\bin\MyTypes.dll</b>
https:///MyService/SharedTypeService.svc?wsdl
现在,客户端代理引用包含数据契约的程序集,并且客户端可以利用其中编码的所有访问器和有用的方法。
使用代码
该代码是一个示例,演示了如何通过引用服务中使用的的数据契约来生成客户端代理。
历史
- 没有更新