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
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
Aucun commentaire:
Enregistrer un commentaire