WCF信道監聽器代碼示例解析
WCF是一個功能比較強大的開發工具,可以幫助我們創建一個功能穩定,安全性高的解決方案。在這里,我們創建一個自定義的信道監聽器:SimpleReplyChannelListner。#t#
該WCF信道監聽器用于在請求-回復消息交換模式下進行請求的監聽。在本案例中,我們來創建與之相對的信道工廠:SimpleChannelFactory< TChannel>,用于請求-回復消息交換模式下進行用于請求發送信道的創建。由于SimpleChannelFactory< TChannel>的實現相對簡單,將所有代碼一并附上。
SimpleChannelFactory< TChannel>直接繼承自抽象基類SimpleChannelFactoryBase< TChannel>。字段成員_innerChannelFactory表示信道工廠棧中后一個信道工廠對象,該成員在構造函數中通過傳入的BindingContext對象的BuildInnerChannelFactory< TChannel>方法創建。OnCreateChannel是核心大方法,實現了真正的信道創建過程,在這里我們創建了我們自定義的信道:SimpleRequestChannel.。構建SimpleRequestChannel. 的InnerChannel通過_innerChannelFactory的CreateChannel方法創建。對于其他的方法(OnOpen、OnBeginOpen和OnEndOpen),我們僅僅通過PrintHelper輸出當前的方法名稱,并調用_innerChannelFactory相應的方法。
WCF信道監聽器代碼示例:
- public class SimpleChannelFactory< TChannel> :
ChannelFactoryBase< TChannel>- {
- public IChannelFactory< TChannel> _innerChannelFactory;
- public SimpleChannelFactory(BindingContext context)
- {
- PrintHelper.Print(this, "SimpleChannelFactory");
- this._innerChannelFactory = context.BuildInnerChannelFactory
< TChannel>();- }
- protected override TChannel OnCreateChannel
(EndpointAddress address, Uri via)- {
- PrintHelper.Print(this, "OnCreateChannel");
- IRequestChannel innerChannel = this._innerChannelFactory.
CreateChannel(address, via) as IRequestChannel;- SimpleRequestChannel. channel = new SimpleRequestChannel.
(this, innerChannel);- return (TChannel)(object)channel;
- }
- protected override IAsyncResult OnBeginOpen
(TimeSpan timeout, AsyncCallback callback, object state)- {
- PrintHelper.Print(this, "OnBeginOpen");
- return this._innerChannelFactory.BeginOpen(timeout, callback, state);
- }
- protected override void OnEndOpen(IAsyncResult result
- {
- PrintHelper.Print(this, "OnEndOpen");
- this._innerChannelFactory.EndOpen(result);
- }
- protected override void OnOpen(TimeSpan timeout)
- {
- PrintHelper.Print(this, "OnOpen");
- this._innerChannelFactory.Open(timeout);
- }
- }
以上就是對WCF信道監聽器的相關介紹。