tags:

views:

235

answers:

1

I have a net tcp PerSession WCF service, my current logic for keeping track the number of connected users (active clients) is using the service constructor and heartbeat mechanism.

in the constructor I just increment a static member, and during sending heartbeat to client if one of these exceptions raises ( TimeoutException, FaultException, CommunicationObjectAbortedException) I decrement the number.

Also I am using heartbeat for sending other stuff. Till now it works perfectly, but is there any better way?

+1  A: 

You can create your implementation of IInstanceContextInitializer which will be notified once new InstanceContext is created.

 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
    }
  }

and attach 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)
    {    }
  }

Once you got access to InstanceContext you can use IncomingChannels property to get the sessionful channels that are incoming to the service instance.

Dzmitry Huba