22 March 2014

Callback Service -- Operations

     Till now we have seen that the all clients will call the service to get the things done. But WCF also provides the service to call the client. In which, service will act as client and client will act as service.
  • HTTP protocols are connectionless nature, so it is not supported for callback operation. So BasicHttpBinding and WSHttpBinding cannot be used for this operation.
  • WCF support WsDualHttpBinding for call back operation.
  • All TCP and IPC protocols support Duplex communication. So all these binding will be used for call back operation.
Defining and configuring a call back contract
       Callback service can be enabled by using CallbackContract property in the Service Contract attribute. In the below example you can find the declaration of the callback contract and it is configured in the Service Contract attribute.

    Public interface IMyContractCallback
    {
        [Operation Contract]
        void OnCallback ();
    }
    [Service Contract (CallbackContract = typeof (IMyContractCallback))]
    Public interface IMyContract
    {
        [Operation Contract ()]
        Void MyMethod();
    }



Client Callback Setup:

As I said earlier, in callback operation client will act as service and service will act as client. So client has to expose a callback endpoint to the service to call. In the earlier part of the tutorial I have mention that InstanceContext is the execution scope of inner most service instance. It provides a constructor that takes the service instance to the host.

  IMyContractCallback call back=new MyCallback ();
  InstanceContext cntx=new InstanceContext (call back);
  MyServiceClient proxy = new MyServiceClient (cntx);
  proxy.MyMethod();  

The client must use a proxy that will set up the bidirectional communication and pass the call back endpoint reference to the service. This can be achieved by creating the proxy using DuplexClientBase

Class MyServiceClient: DuplexClientBase,IMyContract
 {
   Public MyServiceClient (InstanceContext call back Cntx): base(call-back Cntx)
    {           
    }
   Public void MyMethod ()
    {
      base.Channel.MyMethod ();
    }
  }

Service-Side Callback Invocation

The client-side call-back endpoint reference is passed along with every call the client makes to the service, and it is part of the incoming message. The Operation Context class provides the service with easy access to the call-back reference via the generic method GetCallbackChannel<T>( ). Service can call the client side call-back method using reference e to the client side call-back instance. 

The following code shows the call-back method invocation.
IMyContractCallback
CallbackInstance=OperationContext.Current.GetCallbackChannel ();
callbackInstance.OnCallback ();
 







No comments:

Post a Comment