为整个应用程序保留一个wcf客户端代理

本文关键字:一个 wcf 客户端 代理 应用程序 保留 | 更新日期: 2023-09-27 18:25:13

我有高负载的ASP.NET MVC2网站和该网站使用的WCF服务。早期,我每次需要都创建一个代理,甚至没有关闭它。参考我之前的问题(非常感谢SO用户Richard Blewett),我发现我应该关闭这个代理。换句话说,它将成功限制会话。

现在,我正在创建一个代理一次应用程序启动,然后只需检查它,并在需要时重新创建它。所以,这是代码:

public static bool IsProxyValid(MyServ.MyService client) {
    bool result = true;
    if ((client == null) || (client.State != System.ServiceModel.CommunicationState.Opened) // || (client.InnerChannel.State != CommunicationState.Opened)
        )            
        result = false;
    return result;
}
public static AServ.AServClient GetClient(HttpContext http) {            
    if (!IsProxyValid((MyService)http.Application["client"]))
        http.Application["client"] = new MyService();
    return (MyService)http.Application["client"];
}
public static MyServ.MyService GetClient(HttpContextBase http)
{
    if (!IsProxyValid((MyService)http.Application["client"]))
        http.Application["client"] = new MyService();
    return (MyService)http.Application["client"];
}
public ActionResult SelectDepartment(string departments)
    {
       try
        {
            MyService svc = CommonController.GetClient(this.HttpContext);                
            Department[] depsArray = svc.GetData(departments);
            // .... I cut here ....
            return View();
        }
        catch (Exception exc)
        {
            // log here                
            return ActionUnavailable();
        }
    }

你们怎么看?它应该正常工作吗?有时我的应用程序会死机。我认为这是因为客户端代理状态决定不正确,应用程序试图使用损坏的代理。


后期编辑

此外,在TCP监视器中,我看到了许多从站点到服务的已建立连接。为什么它创建了很多连接而不是使用一个全局?也许调用服务方法时发生了一些异常,使其处于故障状态?

希望你们的帮助!

为整个应用程序保留一个wcf客户端代理

我认为在创建新通道之前,如果通道出现故障,您需要中止该通道,并且如果创建新客户端,请确保关闭/中止旧客户端,并使用类似的方法(此方法与单例中的DI一起使用)

public class MyServiceClientInitializer : IMyServiceClientInitializer
 {
        [ThreadStatic]
        private static MyServ.MyService _client;
        public MyServ.MyService Client
        {
            get
            {
                if (_client == null
                    || (_client.State != CommunicationState.Opened
                            && _client.State != CommunicationState.Opening))
                    IntializeClient();
                return _client;
            }
        }
        private void IntializeClient()
        {
            if (_client != null)
            {
                if (_client.State == CommunicationState.Faulted)
                {
                    _client.Abort();
                }
                else
                {
                    _client.Close();    
                }
            }
            string url = //get url;
            var binding = new WSHttpBinding();
            var address = new EndpointAddress(url);
            _client = new MyServ.MyService(binding, address);            
        }
}