I wrote an extension method for use with WCF services that stores all the logic for removing and handling exceptions in one place. The method is as follows:
public static TResult CallMethod<TChannel, TResult>(
this ClientBase<TChannel> proxy,
Func<TResult> func) where TChannel : class
{
proxy.ThrowIfNull("proxy");
func.ThrowIfNull("func");
try
{
return func();
}
finally
{
if (proxy != null)
{
try
{
if (proxy.State != CommunicationState.Faulted)
{
proxy.Close();
}
else
{
proxy.Abort();
}
}
catch (CommunicationException)
{
proxy.Abort();
}
catch (TimeoutException)
{
proxy.Abort();
}
catch (Exception)
{
proxy.Abort();
throw;
}
}
}
}
The method will be used as follows:
public int CreateBusinessObject(BusinessObject item)
{
MyServiceClient proxy = new MyServiceClient();
return proxy.CallMethod(() => proxy.CreateBusinessObject(item));
}
My question is, would it be better than a static method creating a service proxy? I am a little worried about my current implementation. Should building a proxy inside try / catch? My real understanding is that if the constructor fails, nothing is worth it anyway.
source
share