關(guān)于WCF ServiceContract特性簡(jiǎn)介
想要運(yùn)用好一門技術(shù)就要了解它的基本的特性,比如類的特性,我們就來分析一下WCF ServiceContract特性。Windows通信基礎(chǔ)(Windows Communication Foundation,WCF)是基于Windows平臺(tái)下開發(fā)和部署服務(wù)的軟件開發(fā)包(Software Development Kit,SDK)。
#T#WCF為服務(wù)提供了運(yùn)行時(shí)環(huán)境(Runtime Environment),使得開發(fā)者能夠?qū)LR類型公開為服務(wù),又能夠以CLR類型的方式使用服務(wù)。理論上講,創(chuàng)建服務(wù)并不一定需要WCF,但實(shí)際上,使用WCF卻可以使得創(chuàng)建服務(wù)的任務(wù)事半功倍。WCF是微軟對(duì)一系列產(chǎn)業(yè)標(biāo)準(zhǔn)定義的實(shí)現(xiàn),包括服務(wù)交互、類型轉(zhuǎn)換、封送(Marshaling)以及各種協(xié)議的管理。正因?yàn)槿绱?,WCF才能夠提供服務(wù)之間的互操作性。WCF ServiceContract特性允許應(yīng)用到接口或類上。當(dāng)接口應(yīng)用了Service-Contract特性后,需要定義類實(shí)現(xiàn)該接口??偟膩碇v,我們可以使用C#或VB去實(shí)現(xiàn)接口,服務(wù)類的代碼無需修改,自然而然成為一個(gè)WCF服務(wù):
- [ServiceContract]
- interface IMyContract
- {
- [OperationContract]
- string MyMethod();
- }
- class MyService : IMyContract
- {
- public string MyMethod()
- {
- return "Hello WCF";
- }
- }
我們可以隱式或顯式實(shí)現(xiàn)接口:
- class MyService : IMyContract
- {
- string IMyContract.MyMethod()
- {
- return "Hello WCF";
- }
- }
一個(gè)單獨(dú)的類通過繼承和實(shí)現(xiàn)多個(gè)標(biāo)記了WCF ServiceContract特性的接口,可以支持多個(gè)契約。
- [ServiceContract]
- interface IMyContract
- {
- [OperationContract]
- string MyMethod();
- }
- [ServiceContract]
- interface IMyOtherContract
- {
- [OperationContract]
- void MyOtherMethod();
- }
- class MyService : IMyContract,IMyOtherContract
- {
- public string MyMethod()
- {...}
- public void MyOtherMethod()
- {...}
- }
然而,服務(wù)類還有一些實(shí)現(xiàn)上的約束。我們要避免使用帶參構(gòu)造函數(shù),因?yàn)閃CF只能使用默認(rèn)構(gòu)造函數(shù)。同樣,雖然類可以使用內(nèi)部(internal)的屬性、索引器以及靜態(tài)成員,但WCF客戶端卻無法訪問它們。