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 callback operation.
Defining and configuring a callback contract
Callback service can be enabled by using CallbackContract property in the ServiceContract attribute. In the below example you can find the decalration of the callback contract and it is configured in the ServiceContract attribute.
public interface IMyContractCallback { [OperationContract] void OnCallback(); } [ServiceContract(CallbackContract = typeof(IMyContractCallback))] public interface IMyContract { [OperationContract()] 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 callback=new MyCallback(); InstanceContext cntx=new InstanceContext(callback); MyServiceClient proxy = new MyServiceClient(cntx); proxy.MyMethod();
The client must use a proxy that will set up the bidirectional communication and pass the callback endpoint reference to the service. This can be achieved by creating the proxy using DuplexClientBase
class MyServiceClient:DuplexClientBase,IMyContract { public MyServiceClient(InstanceContext callbackCntx) : base(callbackCntx) { } public void MyMethod() { base.Channel.MyMethod(); } }
Service-Side Callback Invocation
The client-side callback endpoint reference is passed along with every call the client makes to the service, and it is part of the incoming message. The OperationContext class provides the service with easy access to the callback reference via the generic method GetCallbackChannel<T>( ). Service can call the client side callback method using reference e to the client side callback instance. The following code shows the callback method invocation.
IMyContractCallback callbackInstance=OperationContext.Current.GetCallbackChannel(); callbackInstance.OnCallback();