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