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
:
I referred few answers on this post and customized it as per my needs.
I wanted the ability to do something with WCF client before using it so the DoSomethingWithClient()
method.
public interface IServiceClientFactory
{
T DoSomethingWithClient();
}
public partial class ServiceClient : IServiceClientFactory
{
public ServiceClient DoSomethingWithClient()
{
var client = this;
// do somthing here as set client credentials, etc.
//client.ClientCredentials = ... ;
return client;
}
}
Here is the helper class:
public static class Service
where TClient : class, ICommunicationObject, IServiceClientFactory, new()
{
public static TReturn Use(Func codeBlock)
{
TClient client = default(TClient);
bool success = false;
try
{
client = new TClient().DoSomethingWithClient();
TReturn result = codeBlock(client);
client.Close();
success = true;
return result;
}
finally
{
if (!success && client != null)
{
client.Abort();
}
}
}
}
And I can use it as:
string data = Service.Use(x => x.GetData(7));