1

在我们的 WCF 项目中,我们singleton pattern用于获取客户端代理。

基本上是因为——

  1. 以后需要的任何增强,在添加 Binding或的客户端对象上Endpoint,都需要最少的更改。
  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接口。所以我认为在这里实现这个接口没有任何害处。

谢谢!

4

1 回答 1

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();
}
于 2012-10-22T14:45:12.217 回答