在我们的WCF项目中,我们使用singleton pattern获取客户端代理。
基本上是因为-
Binding或Endpoint的客户端对象上所需的任何增强都需要最少的更改。为了确保每次服务调用后的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接口。所以我不认为在这里实现这个接口有什么坏处。
谢谢!
发布于 2012-10-22 14:45:12
在我的项目中,我一直在使用一种扩展方法,负责正确关闭服务连接。(我偷了某个博客的扩展方法,忘了那个博客链接)
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();
}https://stackoverflow.com/questions/13000736
复制相似问题