WCF信道監(jiān)聽器代碼示例解析
WCF是一個(gè)功能比較強(qiáng)大的開發(fā)工具,可以幫助我們創(chuàng)建一個(gè)功能穩(wěn)定,安全性高的解決方案。在這里,我們創(chuàng)建一個(gè)自定義的信道監(jiān)聽器:SimpleReplyChannelListner。#t#
該WCF信道監(jiān)聽器用于在請(qǐng)求-回復(fù)消息交換模式下進(jìn)行請(qǐng)求的監(jiān)聽。在本案例中,我們來(lái)創(chuàng)建與之相對(duì)的信道工廠:SimpleChannelFactory< TChannel>,用于請(qǐng)求-回復(fù)消息交換模式下進(jìn)行用于請(qǐng)求發(fā)送信道的創(chuàng)建。由于SimpleChannelFactory< TChannel>的實(shí)現(xiàn)相對(duì)簡(jiǎn)單,將所有代碼一并附上。
SimpleChannelFactory< TChannel>直接繼承自抽象基類SimpleChannelFactoryBase< TChannel>。字段成員_innerChannelFactory表示信道工廠棧中后一個(gè)信道工廠對(duì)象,該成員在構(gòu)造函數(shù)中通過(guò)傳入的BindingContext對(duì)象的BuildInnerChannelFactory< TChannel>方法創(chuàng)建。OnCreateChannel是核心大方法,實(shí)現(xiàn)了真正的信道創(chuàng)建過(guò)程,在這里我們創(chuàng)建了我們自定義的信道:SimpleRequestChannel.。構(gòu)建SimpleRequestChannel. 的InnerChannel通過(guò)_innerChannelFactory的CreateChannel方法創(chuàng)建。對(duì)于其他的方法(OnOpen、OnBeginOpen和OnEndOpen),我們僅僅通過(guò)PrintHelper輸出當(dāng)前的方法名稱,并調(diào)用_innerChannelFactory相應(yīng)的方法。
WCF信道監(jiān)聽器代碼示例:
- 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);
- }
- }
以上就是對(duì)WCF信道監(jiān)聽器的相關(guān)介紹。