I like instantiating my WCF service clients within a using
block as it\'s pretty much the standard way to use resources that implement IDisposable
:
If you don't need IoC or are using an autogenerated client (Service Reference), then you can simple use a wrapper to manage the closing and let the GC take the clientbase when it is in a safe state that will not throw any exception. The GC will call Dispose in serviceclient, and this will call Close
. Since it is alread closed, it cannot cause any damage. I am using this without problems in production code.
public class AutoCloseWcf : IDisposable
{
private ICommunicationObject CommunicationObject;
public AutoDisconnect(ICommunicationObject CommunicationObject)
{
this.CommunicationObject = CommunicationObject;
}
public void Dispose()
{
if (CommunicationObject == null)
return;
try {
if (CommunicationObject.State != CommunicationState.Faulted) {
CommunicationObject.Close();
} else {
CommunicationObject.Abort();
}
} catch (CommunicationException ce) {
CommunicationObject.Abort();
} catch (TimeoutException toe) {
CommunicationObject.Abort();
} catch (Exception e) {
CommunicationObject.Abort();
//Perhaps log this
} finally {
CommunicationObject = null;
}
}
}
Then when you are accessing the server, you create the client and use using
in the autodisconect:
var Ws = new ServiceClient("netTcpEndPointName");
using (new AutoCloseWcf(Ws)) {
Ws.Open();
Ws.Test();
}