[英]Calling WCF service using extension method
我編寫了一個與WCF服務一起使用的擴展方法,它將所有處理和異常處理邏輯保存在一個地方。 方法如下:
public static TResult CallMethod<TChannel, TResult>(
this ClientBase<TChannel> proxy,
Func<TResult> func) where TChannel : class
{
proxy.ThrowIfNull("proxy");
func.ThrowIfNull("func");
try
{
// set client credentials
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;
}
}
}
}
該方法將使用如下:
public int CreateBusinessObject(BusinessObject item)
{
MyServiceClient proxy = new MyServiceClient();
return proxy.CallMethod(() => proxy.CreateBusinessObject(item));
}
我的問題是,這是否會更好地作為創建服務代理的靜態方法? 我有點擔心我目前的實施情況。 代理的構造是否應該在try / catch中? 我目前的理解是,如果構造函數失敗,無論如何都沒有什么可以處理的。
如果構造函數失敗,則整個對象處於無效狀態。 你不應該擔心在這種情況下處置。
對此執行的一個很好的測試是執行以下操作時會發生什么:
class Program
{
static void Main(string[] args)
{
using (new TestClass())
{
Console.WriteLine("In using");
}
}
class TestClass : IDisposable
{
public TestClass()
{
throw new Exception();
}
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
}
結果是永遠不會達到處置。 這是構造函數失敗時發生的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.