一、代码案例
首选建立2个WCF Service,它们分别使用不同的Contract,同时创建一个Console控制台项目,作为Client:
其中,WcfServiceWithDataContract项目使用DataContract,具体表现为将实体类标记为[DataContract]:
[DataContract] public class BookOrder { [DataMember] public string ISBN { get; set; } [DataMember] public string BookTitle { get; set; } [DataMember] public string BookAddress { get; set; } }
注:即使不添加特性DataContract,仍然默认为DataContract。
而WcfServiceWithMessageContract项目使用MessageContract,具体表现为将实体类标记为[DataContract]:
[MessageContract] public class BookOrder { [MessageHeader] public string ISBN { get; set; } [MessageBodyMember] public string BookTitle { get; set; } [MessageBodyMember] public string BookAddress { get; set; } }
但是,两个Service的Operation都是相同的:
public BookOrder PlaceOrder(BookOrder bookOrder) { return new BookOrder() { ISBN = "2", BookTitle = "WPF", BookAddress = "China" }; }
为了观察到更多的端倪,我们将参数和返回值类型都设置为了BookOrder,方法的逻辑只是简单地将参数稍作修改并返回。
二、区别
根据Service的Contract不同(2种),以及在Client端添加Service的方式的不同(也是2种),一共有2*2=4种情形,分析如下:
情形一:UseDCRefDC(在Server端使用DataContract,在Client端生成DataContract)
我们在Client端直接Add Service Reference,指向WcfServiceWithDataContract项目生成的Service:http://localhost:1111/Service1.svc。
同时,在Client端默认生成DataContract:
在Client端(也就是Console控制台项目),调用Service的方式如下:
public static void TestUseDCRefDC() { var client = new UseDCRefDC.Service1Client(); var item = new UseDCRefDC.BookOrder() { ISBN = "1", BookAddress = "USA", BookTitle = "WCF" }; var result = client.PlaceOrder(item); }
情形二:UseMCRefDC(在Server端使用DataContract,在Client端生成MessageContract)
仍然添加对WcfServiceWithDataContract这个WCF Service的引用,并点击Add Service Reference面板中的Advanced按钮,弹出Service Reference Settings面板,将“Always generate message contracts”选项选中:
这时在Client端生成的是MessageContract。
在Client端(也就是Console控制台项目),调用Service的方式如下:
public static void TestUseMCRefDC() { var client = new UseMCRefDC.Service1Client(); var item = new UseMCRefDC.BookOrder() { ISBN = "1", BookAddress = "USA", BookTitle = "WCF" }; PlaceOrderRequest request = new PlaceOrderRequest(item); PlaceOrderResponse response = client.PlaceOrder(request); var result = response.PlaceOrderResult; }
情形三:UseDCRefMC(在Server端使用MessageContract,在Client端生成DataContract)
public static void TestUseDCRefMC() { var client = new UseDCRefMC.Service2Client(); var item = new UseDCRefMC.BookOrder() { ISBN = "1", BookAddress = "USA", BookTitle = "WCF" }; client.PlaceOrder(ref item.ISBN, ref item.BookAddress, ref item.BookTitle); }
情形四:UseMCRefMC(在Server端使用MessageContract,在Client端生成MessageContract)
public static void TestUseMCRefMC() { var client = new UseMCRefMC.Service2Client(); var item = new UseMCRefMC.BookOrder() { ISBN = "1", BookAddress = "USA", BookTitle = "WCF" }; var result = client.PlaceOrder(item); }
参考文章: