2012-10-21 59 views
1

在我们的WCF项目中,我们使用singleton pattern来获取客户端代理。在Singleton上实现IDisposable是否正确

基本上因为 -

  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(); 
    } 
} 

这是否违反了辛格尔顿Design-Pattern原则是什么?任何改善这方面的建议都会有所帮助。

编辑:

考虑using block处置客户对象,如下 -

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

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

谢谢!

+0

我可能是错的,但我没有看到你关闭连接好像你尝试引用/创建新的连接,而不是关闭原来的 –

+0

那么,是你的IDisposable的实现? –

+0

@TonyHopkinson在此处添加代码。 – Abhijeet

回答

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(); 
} 
相关问题