Search code examples
wcfcallback

wcf callback + save session not operationcontext


I'm new to stackoverflow however I use it everyday. Today I need you because I dont get this info anywhere.

My question is: I want to make a service with callback to clients but I dont want to callback in the function they call in the service. (something like subscriber/publisher) I want to save the callback instance. Then I want a service calling a function in my service that will trigger the callbacks(like this: callbacks.PrintMessage("Message"));) Saving the callback instance in a static list in a static class.

When calling the callback.function() Im getting this error: "you are using Disposed object" because Im getting the instance with this: OperationContext.Current.GetCallbackChannel<"callback interface">

What can I do to save that callback instances?

Thanks a lot.

Pedro

CODE:

//FUNCTION IN MY SERVICE
        public void Subscribe()
                {
                   var callback = OperationContext.Current.GetCallbackChannel<IMonitoringWebServiceCallback>();
                    callbacks.Add(callback);

                    callback = OperationContext.Current.GetCallbackChannel<IMonitoringWebServiceCallback>();


                    AlarmCallbackSingleton.Instance.AddCallback(callback);

                    //callback.PrintString("String"); //HERE IT WORKS! BUT I DONT WANT CALL HERE!

                    alarmInfoHandler = new AlarmInfoEventHandler(AlarmInfoHandler);
                    NewAlarmInfo += alarmInfoHandler;
                }

    //FUNCTION IN THE SAME SERVICE CALLED BY OTHER CLIENT
         public void PublishAlarm(string alarm)
                {
                    AlarmInfoEventArgs e = new AlarmInfoEventArgs();
                    e.Alarm = alarm;
                    NewAlarmInfo(this, e); 
                }

        public void AlarmInfoHandler(object sender, AlarmInfoEventArgs e)
                {
        List<IMonitoringWebServiceCallback> callbacks = AlarmCallbackSingleton.Instance.GetCallbacks();

    //EVERYONE THAT SUBSCRIBED SHOULD EXECUTE THIS (HERE I GET THE DISPOSED ERROR)
                    callbacks.ForEach(x => x.ShowString("String!"));
                }

Solution

  • Ok. I got it! The answer to this question is as simple as this:

    When you subscribe to the service you need to save somewhere(List etc..) the OperationContext and not the callback object. Then when the PublishAlarm is called by another client the event is triggered and you need to get OperationContext of all clients that subscribe. I saved that objetcs in a static List(singleton class) just for the example.

    Then:

     public void AlarmInfoHandler(object sender, AlarmInfoEventArgs e)
     {
        var operation = AlarmCallbackSingleton.Instance.operationContext
        var callback = operation.GetCallbackChannel<IMonitoringWebServiceCallback>();
        callback.ShowAlarm(); //function you want to call
     }
    

    Hope this can help!