c# - 使用静态/集中类关闭 WCF 连接

标签 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() 方法接受。每个服务客户端似乎都是一个独特的类,我在其中找不到合适的接口(interface)或基类。例如:

//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。

谢谢!

最佳答案

1: I'd like to avoid creating an override of WCFManager.CloseConnection() for each service client type, but is this the only option I have?

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

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

((ICommunicationObject)alphaServiceClient).CloseConnection();

2: Is this even a good option, or will passing the connection around cause more potential issues?

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

  1. Since I am load balancing my WCF server across 2-4 servers, is closing the connection each time it is used the best option

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

关于c# - 使用静态/集中类关闭 WCF 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27023974/

相关文章:

c# - Windows Phone LonglistSelector 不呈现所有项目

c# - 使用 asp.net 从数据库中检索数据( 'user' 附近的语法不正确)

wcf - 每次更新服务引用时,如何防止 VS2010 创建新的绑定(bind)?

基类上的 WCF 数据契约 knowntype

c# - 如何显示消息框并保持应用程序执行

c# - 在网络服务中使用 p4.net

c# - GridView 排序将页面重置为原始数据

wcf - 为什么我的 WCF 服务没有加载我的绑定(bind)配置?

c# - 使用 Go 编码 UTF-8

asp.net - 更改禁用链接按钮的颜色