8Jul/100
Disposing Proxy calls to WCF Services
How many times have we had this issue, you call a WCF (of infact any other service) and due to some exception the the call to the service is not disposed and will eventually eat up all the resource.
A classic example of such issue is
<pre>
<pre> public void Save(Message message)
{
IService _service = new ServiceClient();
SaveMessageRequest request = new SaveMessageRequest{Message = message};
_service.SaveMessage(request);
}
To resolve this ussye we will make changes in two steps.
Step 1:
We will define a partial class with dispose method.
public partial class ServiceClient : IDisposable { /// <summary> /// A partial class for ServiceClient /// Used to correctly close or abort a WCF proxy call. /// You MUST wrap the proxy call with a USING statement as DISPOSE will ALWAYS be called /// </summary> void IDisposable.Dispose() { // Check to see if the call has faulted if (State == CommunicationState.Faulted) { // We must abort the proxy as closing it will cause an exception Abort(); } else { // Close the proxy Close(); } } }Step 2:
We will change the save method to look as below. This will make sure that before the execution exits the using, the dispose method is called to dispose the service client.
public void Save(Message message)
{
using (ServiceClient smsProxy = new ServiceClient())
{
SaveMessageRequest request = new SaveMessageRequest{Message = message};
smsProxy.SaveMessage(request);
}
}


