Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用静态/集中类关闭WCF连接_C#_Asp.net_Wcf_Nettcpbinding - Fatal编程技术网

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

C# 使用静态/集中类关闭WCF连接,c#,asp.net,wcf,nettcpbinding,C#,Asp.net,Wcf,Nettcpbinding,我想开始实施一个更好的解决方案,在我的代码中关闭我的WCF连接,并在这个过程中处理任何异常问题。我计划实现该解决方案,但不是在我的类中重复这一点,我想编写一个静态类,我可以将打开的连接发送到该类进行关闭和异常处理,如下所示: public static class WCFManager { public static void CloseConnection(ServiceClient serviceClient) { try {

我想开始实施一个更好的解决方案,在我的代码中关闭我的WCF连接,并在这个过程中处理任何异常问题。我计划实现该解决方案,但不是在我的类中重复这一点,我想编写一个静态类,我可以将打开的连接发送到该类进行关闭和异常处理,如下所示:

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:
var alphaServiceClient=新的AlphaService.alphaServiceClient();
alphaServiceClient.Open();
WCFManager.CloseConnection(alphaServiceClient)//
1:我希望避免创建对的覆盖
WCFManager.CloseConnection()用于每个服务客户端类型,但这是
我唯一的选择是什么

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

还有一点小建议:作为
ICommunicationObject
的扩展方法,您所做的工作甚至更好。然后就变成了

((ICommunicationObject)alphaServiceClient).CloseConnection();
2:这甚至是一个好的选择,还是将传递连接 导致更多潜在问题

这是一个助手方法。这很难“绕过连接”。很好

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

  • 对。使用连接并将其关闭

    谢谢,这正是我所希望的答案!