我有一个net tcp PerSession WCF服务,我目前跟踪连接用户数(活动客户端)的逻辑是使用服务构造函数和心跳机制.
在构造函数中,我只增加一个静态成员,并在将心跳发送到客户端期间,如果其中一个异常引发(TimeoutException,FaultException,CommunicationObjectAbortedException),我减少数量.
我也使用心跳发送其他东西.
直到现在它完美无缺,但还有更好的方法吗?
最佳答案 您可以创建
IInstanceContextInitializer的实现,一旦创建新的InstanceContext,将通知该实现.
public class MyInstanceContextInitializer : IInstanceContextInitializer
{
public void Initialize(InstanceContext instanceContext, Message message)
{
// hook up to events to get notified about changes in the state of this instance context.
// remember refernce to it
}
}
并附上它
public class InstanceInitializerBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters)
{ }
//Apply the custom IInstanceContextProvider to the EndpointDispatcher.DispatchRuntime
public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
{
MyInstanceContextInitializer extension = new MyInstanceContextInitializer();
endpointDispatcher.DispatchRuntime.InstanceContextInitializers.Add(extension);
}
public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior)
{ }
public void Validate(ServiceEndpoint endpoint)
{ }
}
一旦访问了InstanceContext,就可以使用IncomingChannels属性来获取传入服务实例的会话通道.