【问题标题】:Is it correct to implement IDisposable on Singleton [closed]在 Singleton 上实现 IDisposable 是否正确[关闭]
【发布时间】:2012-10-21 18:19:42
【问题描述】:

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

基本上是因为-

  1. 以后需要的任何增强,在客户端对象上添加 BindingEndpoint,只需要很少的更改。
  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();
    }
}

这是否违反了 Singleton Design-Pattern 原则?任何改进这一点的建议都会有所帮助。

编辑:

考虑using block 如下处理客户端对象-

using (Service1Client client = new Service1Client())
{
    client.Operation1();
}

这意味着 WCF 代理实现 IDisposable 接口。所以我认为在这里实现这个接口没有任何害处。

谢谢!

【问题讨论】:

  • 我可能是错的,但我没有看到你关闭连接似乎你试图引用/创建新连接而不是关闭原来的连接
  • 那么您的 IDisposable 实现在哪里?
  • @TonyHopkinson 在此处添加代码。
  • 我认为这不应该是单例。
  • 我认为您确实想拥有一家工厂。 IDisposable 用于您想要摆脱的非托管资源。并且处理/关闭代理然后获取另一个实例可能会导致当前代码出现问题。即使您可能已经处置了该对象,它也很有可能不为空。

标签: c# wcf design-patterns


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多