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 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
[ServiceContract(CallbackContract = typeof(IMyContractCallback))]
public interface IMyContract
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);
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
public MyServiceClient(InstanceContext callbackCntx)
public void 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.
- Always create the service with Interface->Implementation format, mention the contract in Interface.
- Define the service in Class library and refer the class library in Host project. Don’t use service class in host project.
- Change the instance mode to per call as default.
- Always catch exception using try/catch block and throw exception using FaultException < T >.
- Logging and Include exception should be enable while compiling the project in debug mode. While in production deployment disable the logging and Include exception details.