I have always learned that never use using statement when calling WCF Service like this
using (Service.YourClientProxy client = new Service.YourClientProxy())
{
var time = client.Time();
}
So I am always using this to call Service
YourClientProxy clientProxy = new YourClientProxy();
try
{
.. use your service
clientProxy.Close();
}
catch(FaultException)
{
clientProxy.Abort();
}
catch(CommunicationException)
{
clientProxy.Abort();
}
catch (TimeoutException)
{
clientProxy.Abort();
}
I have been reading och stackoverflow and I have read this post here Service.cs class taken from stackoverflow
I would like to know if this below is a good practice to call WCF service and does this really close the service?
public static class Service<TChannel>
{
public static ChannelFactory<TChannel> ChannelFactory = new ChannelFactory<TChannel>("*");
public static TReturn Use<TReturn>(Func<TChannel, TReturn> codeBlock)
{
var proxy = (IClientChannel)ChannelFactory.CreateChannel();
var success = false;
try
{
var result = codeBlock((TChannel)proxy);
proxy.Close();
success = true;
return result;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}
Invoking service from client like this.
var time = Service<Service.YourServiceChannel>.Use(resultAsync =>
{
return resultAsync.TimeAsync();
});