今天看了,Artech的wcf後續,感覺十分不錯,做了一下簡單的小結,
wcf,在用戶端自動產生的執行個體中 是從ClientBase<of T>.Channel屬性開始的,最終要建立T的透明代理,然後調用。
以BasicHttpBinding為例,
用戶端請求的主要步驟如下:
1 根據傳入的Binding和EndpointAddress產生ServiceEndpoint
2 再根據ServiceEndpoint的類型產生ServiceChannelFactory 類的執行個體
當前BasicHttpBinding 產生的應該是ServiceChannelFactoryOverRequest類的執行個體,
對應的IChannelBinder是RequestChannelBinder
註:
basicHttpBinding.BuildChannelFactory<IRequestChannel>要對 basicHttpBinding所有的繫結元素進行遍曆
預設情況下,不啟用https,則傳輸元素使用HttpTransportBindingElement,該對象重寫BuildChannelFactory<IRequestChannel>,傳回值是HttpChannelFactory
RequestChannelBinder對象最重要的欄位是channel,對應的值是HttpChannelFactory.CreateChannel(),返回的值是HttpChannelFactory.HttpRequestChannel
3 產生ServiceChannel,將ServiceChannelFactoryOverRequest和RequestChannelBinder做為參數傳入ServiceChannel
建構函式為ServiceChannel(ServiceChannelFactory factory, IChannelBinder binder)
4. 產生T的透理代理ServiceChannelProxy,將ServiceChannel做為參數傳入ServiceChannelProxy,構造
5.在調用透明代理相應的方法時,調用ServiceChannelProxy.Invoke(),
如果是Service,調用ServiceChannel.Call(),此時實質是調用ServiceChannel封裝的IChannelBinder(當前是RequestChannelBinder)的call,
6 調用RequestChannelBinder.Request(),注意步驟2最後一句,此時channel是HttpChannelFactory.HttpRequestChannel
HttpChannelFactory.HttpRequestChannel建立 HttpChannelRequest的請求,然後調用HttpChannelRequest.SendRequest發送訊息
其實質就是封裝一個HttpWebRequest,將Message發送到伺服器端address裡,根,webservice的最終原理是一樣的
因此,要抓住幾個關係點,從總體上把握用戶端請求的流程
(1 ServiceChannelFactory 類的執行個體是什麼類型
(2 IChannelBinder介面的實現是什麼類型
(3 IChannelBinder.Channel是什麼
BindingElement.BuildChannelFactory<TChannel>
這個方法很有意思,預設的實現是通用BindingContext
將當前Binding對象中的所有元素(BindingElementCollection對象的執行個體),one by one 的進行遍曆,每次移走一個,取出,然後再次調用BuildChannelFactory<TChannel>
舉個例子
對於BasicHttpBinding對象來說,封裝了
傳輸繫結項目
HttpsTransportBindingElement httpsTransport;
指定 HTTPS 傳輸以傳輸訊息的繫結元素。
HttpTransportBindingElement httpTransport;
用於指定 HTTP 傳輸以傳輸訊息的繫結元素
協議通道元素 (安全)
BasicHttpSecurity security;
配置 basicHttpBinding 綁定的安全設定。
訊息編碼繫結元素
MtomMessageEncodingBindingElement mtomEncoding;
指定訊息傳輸最佳化機制 (MTOM) 訊息所使用的編碼和版本管理的繫結元素。
TextMessageEncodingBindingElement textEncoding;
指定用於基於文本的 SOAP 訊息的字元編碼與訊息版本管理。
此時,BindingElementCollection中有以上元素,先從集合中移出一個,
調用一次BuildChannelFactory<TChannel>
HttpTransportBindingElement httpTransport 重寫了BuildChannelFactory<TChannel> 返回 HttpChannelFactory
其它的繫結元素基本上調BindingElement的,是直接跳到下一個,
所以,
BasicHttpBinding.BuildChannelFactory<IRequestChannel>()返回的是
HttpChannelFactory