当客户端引用WCF服务时,必须为服务定义一个唯一的命名空间。在默认情况下,这个服务中所用到的类会被导入到这个命名空间内。这样,在不同的服务内引用同一个数据契约时就会遇到一个问题:在客户端,同一个数据契约被导入到不同的命名空间中,无法实现转换。

在以下例子中,PersonService与ContractService同时包括对Person数据契约的引用,但通过 PersonService获取到的Person对象,无法作为ContractService中的参数,因为在客户端,它们被引用到不同的命名空间之 中,被视为不同的两个类。

1:      [ServiceContract]
2:      public interface IPersonService
3:      {
4:          [OperationContract]
5:          Person GetPerson();
6:      }
7:   
8:      public class PersonService : IPersonService
9:      {
10:          public Person GetPerson()
11:          {
12:              Person person = new Person();
13:              person.ID = 0;
14:              person.Name = "Leslie";
15:              person.Age = 34;
16:              return person;
17:          }
18:      }
19:   
20:      [ServiceContract]
21:      public interface IContractService
22:      {
23:          [OperationContract]
24:          Contract GetContractByPerson(Person person);
25:      }
26:   
27:      public class ContractService : IContractService
28:      {
29:          public Contract GetContractByPerson(Person person)
30:          {
31:              Contract contract=ContractManager.GetContractByPerson(person);
32:              .....
33:              return contract;
34:          }
35:      }
36:   

从Visual Studio 2008开始,系统为客户提供了“共享数据契约”这一功能。首先把需要共享的数据契约包含在一个程序集中,生成一个Model.dll文件。在客户端引用 这一程序集,在添加服务引用时,选择"高级"—>"重新使用引用的程序集中的类型(R)"—>"重新使用所引用的指定程序集中的类型 (S)",然后选择Model。这样,在客户端就会同时使用Model.dll中的Person对象。