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信道监听器的相关介绍。