2015-02-10 66 views
0

我有一個創建我的WCF服務客戶端的類。在關閉超時時創建WCF客戶端的新實例?

是否有可能創建新的實例,每當服務超時?我的意思是每次出,關,開,接。但閉幕對我來說更重要。

如下所示:

public class ServiceClientFactory 
{ 
    private static SmartServiceClient _client; 
    internal SmartServiceClient Client 
    { 
     get 
     { 
      if (_client is not closed && _client != null) return _client; 
      _client = new SmartServiceClient(); 
      return _client; 
     } 
    } 
} 
+0

此代碼似乎創建調用服務的客戶端,而不是服務本身 – 2015-02-10 08:48:21

+0

@TomRedfern:你說得對。我實際需要它,我編輯了標題 – 2015-02-10 08:53:09

+1

僅供參考編輯我的答案以簡化代碼 – 2015-02-10 14:40:37

回答

1

首先,你需要修改你的工廠代碼 - 你還需要檢查的Faulted狀態:

if (_client != null) 
{ 
    if (_client.State == CommunicationState.Faulted) 
    { 
     _client.Abort(); // Use when channel is faulted 
    } 

    // Now you can check for closed state etc... 
    else if (_client.State != CommunicationState.Closed) 
    { 
     return _client; 
    } 
} 

_client = new SmartServiceClient(); 
return _client; 

如果有一個超時異常通道將處於故障狀態,所以下一次你嘗試讓你的客戶...

var client = ServiceClientFactory.Client; // Client is renewed here. 

...你會得到一個新的實例。