会话信道 从状态保持的角度,可以把信道分为数据报信道(Datagram Channel)和会话信道(Sessionful Channel)。前者不需要保持具体的客户端(服务代理)的状态,因此多个客户端对象可以使用相同的信道;后者则绑定一个客户端对象,并且与客户端对象具有相同的生命周期。 WCF中的会话(Session)表示在进行通信的参与者之间共享的上下文,会话通过消息关联(Message Correlation)的方式来实现。所谓的消息关联,就是将发送自相同客户端的消息通过一个会话ID关联在一起。关于会话,在本册的第9章“实例化与会话(Instancing and Session)”中有详细的介绍。 ISession WCF通过接口System.ServiceModel.Channels.ISession表示会话,ISession中通过唯一的属性成员Id标识一个会话。请求消息与会话ID进行关联,便知道了它源自哪个客户端。 public interface ISession { string Id { get; } } WCF定义了一系列额外接口来表示基于不同的消息交换模式和信道形状下的会话,这些接口直接或间接地继承自ISession接口,它们包括具有如下定义的接口IOutputSession、IInputSession和IDuplexSession。 public interface IInputSession : ISession {} public interface IOutputSession : ISession {} public interface IDuplexSession : IInputSession, IOutputSession, ISession { IAsyncResult BeginCloseOutputSession(AsyncCallback callback, object state); IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state); void CloseOutputSession(); void CloseOutputSession(TimeSpan timeout); void EndCloseOutputSession(IAsyncResult result); } 如上面的代码片段所示,IOutputSession和IInputSession下并没有定义任何成员。IDuplexSession继承IInputSession、IOutputSession和ISession,并定义了一系列CloseOutputSession和BeginCloseOutputSession/EndCloseOutputSession方法用于关闭会话。 ISessionChannel<TSession> 会话机制是通过会话信道(栈)实现的,所有会话信道直接或间接地实现了具有如下定义的接口System.ServiceModel.Channels.ISessionChannel<TSession>,泛型参数TSession实现了接口ISession。 public interface ISessionChannel<TSession> where TSession : ISession { TSession Session { get; } } 上面定义的一系列基于相应信道形状的接口均具有对应的支持会话的版本,包括IOutputSessionChannel/IInputSessionChannel、IRequestSessionChannel/IReplySessionChannel 和IDuplexSessionChannel。如下面的代码片段所示,它们直接或间接地继承ISessionChannel <TSession>。 public interface IOutputSessionChannel : IOutputChannel, IChannel, ICommunicationObject, ISessionChannel<IOutputSession> {} public interface IInputSessionChannel : IInputChannel, IChannel, ICommunicationObject, ISessionChannel<IInputSession> {} public interface IRequestSessionChannel : IRequestChannel, IChannel, ICommunicationObject, ISessionChannel<IOutputSession> {} public interface IOutputSessionChannel : IOutputChannel, IChannel, ICommunicationObject, ISessionChannel<IOutputSession> {} public interface IDuplexSessionChannel : IDuplexChannel, IInputChannel, IOutputChannel, IChannel, ICommunicationObject, ISessionChannel<IDuplexSession> {}