What is the best workaround for the WCF client `using` block issue?

前端 未结 26 2184
余生分开走
余生分开走 2020-11-22 00:03

I like instantiating my WCF service clients within a using block as it\'s pretty much the standard way to use resources that implement IDisposable:

26条回答
  •  不要未来只要你来
    2020-11-22 00:34

    If you don't need IoC or are using an autogenerated client (Service Reference), then you can simple use a wrapper to manage the closing and let the GC take the clientbase when it is in a safe state that will not throw any exception. The GC will call Dispose in serviceclient, and this will call Close. Since it is alread closed, it cannot cause any damage. I am using this without problems in production code.

    public class AutoCloseWcf : IDisposable
    {
    
        private ICommunicationObject CommunicationObject;
    
        public AutoDisconnect(ICommunicationObject CommunicationObject)
        {
            this.CommunicationObject = CommunicationObject;
        }
    
        public void Dispose()
        {
            if (CommunicationObject == null)
                return;
            try {
                if (CommunicationObject.State != CommunicationState.Faulted) {
                    CommunicationObject.Close();
                } else {
                    CommunicationObject.Abort();
                }
            } catch (CommunicationException ce) {
                CommunicationObject.Abort();
            } catch (TimeoutException toe) {
                CommunicationObject.Abort();
            } catch (Exception e) {
                CommunicationObject.Abort();
                //Perhaps log this
    
            } finally {
                CommunicationObject = null;
            }
        }
    }
    

    Then when you are accessing the server, you create the client and use using in the autodisconect:

    var Ws = new ServiceClient("netTcpEndPointName");
    using (new AutoCloseWcf(Ws)) {
    
        Ws.Open();
    
        Ws.Test();
    }
    

提交回复
热议问题