2012-10-21 61 views
1

在我們的WCF項目中,我們使用singleton pattern來獲取客戶端代理。在Singleton上實現IDisposable是否正確

基本上因爲 -

  1. 後所需的任何功能增強,客戶對象添加 BindingEndpoint上,將需要最小的改變。
  2. 我們不會同時調用多個服務。

要確保connection is closed每一個服務調用後正常,我們計劃實現單IDisposable如下 -

public class ClientSingleton : IDisposable 
{ 
    static Service1Client client; 
    private ClientSingleton() 
    { 
     client = new Service1Client(); 
    } 
    public Service1Client getInstance() 
    { 
     if (client != null) 
      return client; 
     else 
     { 
      client = new Service1Client(); 
      return client; 
     } 
    } 
    public void Dispose() 
    { 
     client.Close(); 
    } 
} 

這是否違反了辛格爾頓Design-Pattern原則是什麼?任何改善這方面的建議都會有所幫助。

編輯:

考慮using block處置客戶對象,如下 -

using (Service1Client client = new Service1Client()) 
{ 
    client.Operation1(); 
} 

這意味着WCF代理實現IDisposable接口。所以我認爲在這裏實現這個接口沒有任何壞處。

謝謝!

+0

我可能是錯的,但我沒有看到你關閉連接好像你嘗試引用/創建新的連接,而不是關閉原來的 –

+0

那麼,是你的IDisposable的實現? –

+0

@TonyHopkinson在此處添加代碼。 – Abhijeet

回答

1

我一直在我的項目中使用擴展方法,負責正確關閉服務連接。 (我偷了一些博客的擴展方法,我忘了,博客鏈接)

public static void CloseConnection(this ICommunicationObject client) 
{ 
    if (client.State != CommunicationState.Opened) 
    { 
    return; 
    } 

    try 
    { 
    client.Close(); 
    } 
    catch (CommunicationException) 
    { 
    client.Abort(); 
    throw; 
    } 
    catch (TimeoutException) 
    { 
    client.Abort(); 
    throw; 
    } 
    catch (Exception) 
    { 
    client.Abort(); 
    throw; 
    } 
} 

不像你的方法(這是針對特定的代理服務器),這可以在任何代理用於安全地關閉連接。

用法示例

Service1Client client = null 

try 
{ 
    client = new Service1Client(); 
} 
finally 
{ 
    if(client != null) 
    client.CloseConnection(); 
} 
相關問題