In our WCF project, we are using singleton pattern to obtain client proxy.
Basically because-
- Any enhancements required later, on the client object adding
BindingorEndpoint, would require minimal changes. - We do not call multiple service, at the same time.
To make sure that connection is closed properly after each service call, We are planning to implement IDisposable in singleton as below –
public class ClientSingleton : IDisposable
{
static Service1Client client;
private ClientSingleton()
{
client = new Service1Client();
}
public Service1Client getInstance()
{
if (client != null)
return client;
else
{
client = new Service1Client();
return client;
}
}
public void Dispose()
{
client.Close();
}
}
Does this violates Singleton Design-Pattern principles? Any advice to improve this would be helpful.
edit:
Consider using block to dispose the client object as below –
using (Service1Client client = new Service1Client())
{
client.Operation1();
}
That means WCF proxies implement IDisposable interface. So I don’t see any harm in implementing this interface here.
Thanks!
I have been using an extension method in my project that takes care of closing the service connection properly. (I stole the extension method from some blog and I forgot that blog link)
Unlike your approach (which is specific to a particular proxy) this can be used on any proxy to close the connection safely.
Example usage