Identifying clients in a WCF service

2019-04-28 11:07发布

问题:

I have a working duplex WCF service with WSDualHttpBinding. My problem is figuring out a way to store the callback channel with a unique id. The service is intended to be long-running. Can I simply grab the OperationContext.Current.GetCallbackChannel() return value when a "Subscribe" method is called and store it in a list or dictionary? Is it guaranteed to be valid until the connection is alive?

回答1:

The easiest way would be to have the client submit a key value in the Subscribe method of your service. You could then save the Callback channel in a dictionary. This dictionary would probably need to be a static variable or singleton class whose lifespan is greater than the Service Class's lifespan since most service class's have a PerCall lifetime and get disposed of after the service call is complete. Beware of threading issues!

The callback channel can be faulted at any time either on the client or the service side. The service has to handle the possibility of a faulted channel and to remove the faulted channel from the dictionary. WSDuallHttpBinding is a "Stateless" binding so any faults in the client won't be detected on the service side until the service side attempts to call them. NetTcpBinding will raise the ChannelFaulted event if the client gets into a faulted state. For that reason I would recommend the NetTcpBinding if it fits your requirements.

public bool Subscribe(string id) {
        ICallback callback = OperationContext.Current.GetCallbackChannel();
        if (!_activeCallbackChannels.Contains(id)) {
            _activeCallbackChannels.Add(id, callback);
            return true;
        }
        else {
            return false;
        }

    }