使用静态/集中式类关闭WCF连接

时间:2014-11-19 18:11:47

标签: c# asp.net wcf nettcpbinding

我想开始实现一个更好的解决方案,用于在我的代码中关闭我的WCF连接,以及在该过程中处理异常的任何问题。我计划实现解决方案found here,而不是在我的类中复制它,我想编写一个静态类,我可以发送我的开放连接以进行闭包和异常处理,如下所示:

public static class WCFManager
{
    public static void CloseConnection(ServiceClient serviceClient)
    {
        try
        {
            serviceClient.Close();
        }
        catch (CommunicationException e)
        {
            var error = e.Message;
            serviceClient.Abort();
            //TODO: Log error for communication exception
        }
        catch (TimeoutException e)
        {
            var error = e.Message;
            serviceClient.Abort();
            //TODO: Log error for timeout exception
        }
        catch (Exception e)
        {
            var error = e.Message;
            serviceClient.Abort();
            //TODO: Log error for exception
        }
    }
}

我遇到的问题是我有很多服务客户端类型,我不确定基类是什么,我应该针对WCFManager.CloseConnection()方法接受。每个服务客户端似乎都是一个唯一的类,我找不到合适的接口或基类。例如:

//Inside Class1:
var alphaServiceClient = new AlphaService.AlphaServiceClient();
alphaServiceClient.Open();
WCFManager.CloseConnection(alphaServiceClient); //<-- Requires AlphaServiceClient type

//Inside Class2:
var betaServiceClient = new BetaService.BetaServiceClient();
betaServiceClient.Open();
WCFManager.CloseConnection(betaServiceClient); //<-- Requires BetaServiceClient type

问题:

1:我想避免为每个服务客户端类型创建WCFManager.CloseConnection()的覆盖,但这是我唯一的选择吗?

2:这是一个不错的选择,还是通过连接导致更多潜在问题?

3。由于我在两台服务器之间对我的WCF服务器进行负载均衡,每次使用时都关闭连接是最佳选择,或者每次为每个ServiceClient创建一个静态引用。更好的方案(我很确定它不是,但是会对此有第二种意见!)

仅供参考:我正在使用NetTcpBinding并在解决方案资源管理器中添加ServiceReferences。

谢谢!

1 个答案:

答案 0 :(得分:2)

  

1:我想避免创建覆盖   每个服务客户端类型的WCFManager.CloseConnection(),但是这个   我唯一的选择?

所有WCF代理都从ICommunicationObject继承。这实际上是定义Abort()和Close()方法的接口。要调用您的方法,请始终首先转换为ICommunicationObject

同样轻微的建议:你所做的工作作为ICommunicationObject的扩展方法更有效。然后就变成了

((ICommunicationObject)alphaServiceClient).CloseConnection();
  

2:这是一个不错的选择,还是会通过连接   导致更多潜在问题?

这是一个帮助方法。它几乎没有“绕过连接”。很好。

  
      
  1. 由于我在两台服务器上对我的WCF服务器进行负载均衡,因此每次使用时都关闭连接是最佳选择
  2.   

是。使用连接并关闭它。