2015-02-10 69 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. 

...你会得到一个新的实例。