Proxy error and disposing management is a common issue when you start with WCF. When you use a proxy, a channel is open and it's your responsability to close connection and manage errors and ressource disposing.
All these operations are fastidious, time consuming and make code more complexe.
The solution is to wrap all these operations into a single generic class who implements IDisposable in order to use it in an using block.
For example,
DocumentDTO[] list;
using (ServiceProxyWrapper<ContentClient>
wrapper = new
ServiceProxyWrapper<ContentClient>())
{
list = wrapper.Proxy.List(channel);
}
Thanks that, your code become more readable, more solid and more business oriented.
Complete wrapped implementation are below :
public class ServiceProxyWrapper : IDisposable
where TProxy : class, ICommunicationObject, IDisposable, new()
{
private bool disposed;
private TProxy proxy;
public ServiceProxyWrapper()
{
this.proxy = new TProxy();
}
public TProxy Proxy
{
get
{
if (this.proxy != null)
{
return this.proxy;
}
else
{
throw new ObjectDisposedException
("ServiceProxyWrapper");
}
}
}
#region IDisposable Membres
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
~ServiceProxyWrapper()
{
this.Dispose(false);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
try
{
if (this.proxy != null)
{
if (this.proxy.State !=
CommunicationState.Faulted)
{
this.proxy.Close();
}
else
{
this.proxy.Abort();
}
}
}
catch (CommunicationException)
{
this.proxy.Abort();
}
catch (TimeoutException)
{
this.proxy.Abort();
}
catch (Exception)
{
this.proxy.Abort();
throw;
}
finally
{
this.proxy = null;
}
this.disposed = true;
}
}
#endregion
}Référence :
http://weblogs.asp.net/cibrax/archive/2009/06/26/disposing-a-wcf-proxy.aspx