CommunicationObject
WCF绑定模型涉及多种类型的组件,比如信道、信道监听器、信道工厂等。从功能上讲,这些对象都是为通信服务的,可以把它们称为通信对象(Communication Object)。对于这些通信对象来说,它们具有相同的状态和状态转换方式(状态机),所以WCF提供了具有如下定义的System.ServiceModel.ICommunicationObject接口来统一管理通信对象的状态机。
public interface ICommunicationObject
{
//事件
event EventHandler Closed;
event EventHandler Closing;
event EventHandler Faulted;
event EventHandler Opened;
event EventHandler Opening;
//开启
void Open();
void Open(TimeSpan timeout);
IAsyncResult BeginOpen(AsyncCallback callback, object state);
IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object
state);
void EndOpen(IAsyncResult result);
//关闭
void Close();
void Close(TimeSpan timeout);
IAsyncResult BeginClose(AsyncCallback callback, object state);
IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object
state);
void EndClose(IAsyncResult result);
//中止
void Abort();
//属性
CommunicationState State { get; }
}
ICommunicationObject具有一个System.ServiceModel.CommunicationState枚举类型的State属性表示通信对象当前所处的状态。如下所示的6个枚举值体现了6种典型的状态:被创建(Created)、正被开启(Opening)、已经被开启(Opened)、正关闭(Closing)、已关闭(Closed)、出错(Faulted)。
public enum CommunicationState
{
Created,
Opening,
Opened,
Closing,
Closed,
Faulted
}
接口ICommunicationObject具有5个事件,其中Opening/Opened和Closing/Closed分别在通信对象开启和关闭前后被触发,而当通信对象状态转换为Faulted之后会触发Faulted事件。定义在接口ICommunicationObject中的Open、Close和Abort方法对应着通信对象开启、关闭和中止这三种基本的操作,而这些方法同时具有同步和异步版本。
除了ICommunicationObject接口之外,WCF还为具体的通信对象类型定义了一个System.ServiceModel.Channels.CommunicationObject抽象类。如下面的代码片段所示,CommunicationObject实现了ICommunicationObject接口。
public abstract class CommunicationObject : ICommunicationObject
{
//省略成员
}
绑定模型的很多对象都直接或者间接地继承自CommunicationObject。比如说,作为所有信道的基类System.ServiceModel.Channels.ChannelBase是CommunicationObject的直接子类。信道工厂的基类System.ServiceModel.Channels.ChannelFactoryBase和信道管理器的基类System.ServiceModel.Channels.ChannelListenerBase都继承自作为信道管理器的基类System. ServiceModel.Channels.ChannelManagerBase。而ChannelManagerBase也是CommunicationObject的直接子类。图3-5所示的类图反映了ICommunicationObject、CommunicationObject、ChannelBase、ChannelManagerBase、ChannelFactoryBase和ChannelListenerBase之间的继承关系。
图3-5 CommunicationObject继承关系