我从处理异常和潜在退休的自定义“使用”语句进行所有 WCF 调用。我的代码可选地允许我将策略对象传递给语句,以便我可以轻松地更改行为,例如如果我不想重试错误。
代码的要点如下:
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ProxyUsing<T>(ClientBase<T> proxy, Action action)
where T : class
{
try
{
proxy.Open();
using(OperationContextScope context = new OperationContextScope(proxy.InnerChannel))
{
//Add some headers here, or whatever you want
action();
}
}
catch(FaultException fe)
{
//Handle stuff here
}
finally
{
try
{
if(proxy != null
&& proxy.State != CommunicationState.Faulted)
{
proxy.Close();
}
else
{
proxy.Abort();
}
}
catch
{
if(proxy != null)
{
proxy.Abort();
}
}
}
}
然后,您可以使用如下调用:
ProxyUsing<IMyService>(myService = GetServiceInstance(), () =>
{
myService.SomeMethod(...);
});
NoInlining 调用可能对您来说并不重要。我需要它,因为我有一些自定义日志记录代码可以记录异常后的调用堆栈,因此在这种情况下保留该方法层次结构很重要。