【问题标题】:Closing WCF connections using a static/centralized class使用静态/集中类关闭 WCF 连接
【发布时间】:2014-11-19 18:11:47
【问题描述】:

我想开始实施一个更好的解决方案来关闭我的整个代码中的 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. 由于我在 2-4 台服务器之间对 WCF 服务器进行负载平衡,因此每次使用最佳选项时都关闭连接,或者创建对每个 ServiceClient 的静态引用一次更好的方案(我很确定不是,但希望对此有第二意见!)

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

谢谢!

【问题讨论】:

    标签: c# asp.net wcf nettcpbinding


    【解决方案1】:

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

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

    还有一个小建议:作为ICommunicationObject 的扩展方法,您正在做的工作会更好。然后就变成了

    ((ICommunicationObject)alphaServiceClient).CloseConnection();
    

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

    这是一个辅助方法。它几乎没有“绕过连接”。没关系。

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

    是的。使用连接并关闭它。

    【讨论】:

    • 谢谢,这正是我希望得到的答案!
    猜你喜欢
    • 2019-04-16
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多