共用方式為


建立 BindingElement

系結和綁定項(分別擴充 System.ServiceModel.Channels.BindingSystem.ServiceModel.Channels.BindingElement的物件)是 Windows Communication Foundation (WCF) 應用程式模型與通道處理站和通道接聽程式相關聯的位置。 如果沒有系結,使用自定義通道需要在通道層級進行程序設計,如 Service Channel-Level ProgrammingClient Channel-Level 程式設計中所述。 本主題討論在 WCF 中啟用使用您的通道的最低需求、開發適用於您通道的 BindingElement,以及從應用程式啟用使用功能,如 開發通道 中第 4 步所述。

概觀

在您的通道中建立BindingElement,可讓開發人員於WCF 應用程式中使用。 BindingElement 物件可以從 System.ServiceModel.ServiceHost 類別使用,將 WCF 應用程式連線到您的通道,而不需要了解通道的精確類型資訊。

BindingElement建立 之後,您可以遵循開發通道中所述的其餘通道開發步驟,根據需求啟用更多功能。

新增綁定項

若要實作自定義 BindingElement,請撰寫繼承自 BindingElement的類別。 例如,如果您已開發出一個可以將ChunkingChannel大型訊息分解成區塊,並在另一端重新組合的通道,則可以透過實作BindingElement並設定系結來使用之,以在任何系結中使用該通道。 本主題的其餘部分會使用 ChunkingChannel 作為範例,示範實作綁定項的需求。

ChunkingBindingElement負責建立 ChunkingChannelFactoryChunkingChannelListener。 它會覆寫 CanBuildChannelFactoryCanBuildChannelListener 實作,並檢查類型參數是否為 IDuplexSessionChannel (在我們的範例中,這是 唯一支援的 ChunkingChannel通道圖形),而且系結中的其他綁定項支援這個通道圖形。

BuildChannelFactory 先檢查要求的通道圖形是否可以建置,然後取得要區塊化的訊息動作清單。 然後,它會建立新的 ChunkingChannelFactory,並將它傳遞至內部通道處理站。 (如果您要建立傳輸綁定項,該元素是系結堆疊中的最後一個專案,因此必須建立通道接聽程式或通道處理站。

BuildChannelListener 擁有可建立 ChunkingChannelListener 並傳遞至內部通道接聽程式的相似實作。

另一個使用傳輸通道的範例是 Transport, UDP,該範例提供以下覆寫。

在範例中,綁定項是 UdpTransportBindingElement,其衍生自 TransportBindingElement。 它會覆寫下列方法來建立與信道相關聯的工廠。

public IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)  
{  
    return (IChannelFactory<TChannel>)(object)new UdpChannelFactory(this, context);  
}  
  
public IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)  
{  
    return (IChannelListener<TChannel>)(object)new UdpChannelListener(this, context);  
}  

它也包含用於複製 BindingElement 以及傳回我們的方案 (soap.udp) 的成員。

通訊協議綁定項

新的綁定項可以取代或增強任何包含的綁定項、新增傳輸、編碼或更高層級的通訊協定。 若要建立新的通訊協議綁定項,請從擴充 BindingElement 類別開始。 您至少必須實作 BindingElement.Clone 並使用 ChannelProtectionRequirements 實作 IChannel.GetProperty。 這會傳回 ChannelProtectionRequirements 給這個綁定項。 如需詳細資訊,請參閱ChannelProtectionRequirements

Clone 應該傳回這個綁定項的新複本。 最佳做法是,建議綁定元素作者使用呼叫基底複製建構函式的複製建構函式來實作 Clone,然後複製此類別中的任何其他欄位。

傳輸綁定項

若要建立新的傳輸綁定項,請擴充 TransportBindingElement 介面。 您至少必須實現 Clone 方法和 TransportBindingElement.Scheme 屬性。

Clone – 應該傳回這個 Binding 元素的全新複本。 最佳做法是,我們建議 Binding Element 作者先以複製建構函式來呼叫基底複製建構函式,再複製此類別中的任何其他欄位來實作 Clone。

Scheme Scheme– get 屬性會傳回綁定項所表示之傳輸通訊協定的 URI 配置。 例如, System.ServiceModel.Channels.HttpTransportBindingElementSystem.ServiceModel.Channels.TcpTransportBindingElement 會從各自的 Scheme 屬性傳回 「HTTP」 和 「net.tcp」。

編碼綁定元素

若要建立新的編碼綁定項,請先擴充 BindingElement 類別並實作 System.ServiceModel.Channels.MessageEncodingBindingElement 類別。 至少,您必須先實作 CloneMessageEncodingBindingElement.CreateMessageEncoderFactory 方法和 MessageEncodingBindingElement.MessageVersion 屬性。

如需使用者定義編碼綁定項之選擇性方法和屬性的完整清單,請參閱 MessageEncodingBindingElement

如需建立新綁定項的詳細資訊,請參閱 建立 User-Defined 系結。

建立通道的綁定項之後,請返回 開發通道 主題,以查看您是否要將組態檔支援新增至綁定項、是否以及如何新增元數據發行集支援,以及是否以及如何建構使用綁定項的使用者定義系結。

另請參閱