我有一个用于创建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 :(得分: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.
...你会得到一个新实例。