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

前端 未结 26 1698
余生分开走
余生分开走 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:10

    Override the client's Dispose() without the need to generate a proxy class based on ClientBase, also without the need to manage channel creation and caching! (Note that WcfClient is not an ABSTRACT class and is based on ClientBase)

    // No need for a generated proxy class
    //using (WcfClient orderService = new WcfClient())
    //{
    //    results = orderService.GetProxy().PlaceOrder(input);
    //}
    
    public class WcfClient : ClientBase, IDisposable
        where TService : class
    {
        public WcfClient()
        {
        }
    
        public WcfClient(string endpointConfigurationName) :
            base(endpointConfigurationName)
        {
        }
    
        public WcfClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public WcfClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public WcfClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
        {
        }
    
        protected virtual void OnDispose()
        {
            bool success = false;
    
            if ((base.Channel as IClientChannel) != null)
            {
                try
                {
                    if ((base.Channel as IClientChannel).State != CommunicationState.Faulted)
                    {
                        (base.Channel as IClientChannel).Close();
                        success = true;
                    }
                }
                finally
                {
                    if (!success)
                    {
                        (base.Channel as IClientChannel).Abort();
                    }
                }
            }
        }
    
        public TService GetProxy()
        {
            return this.Channel as TService;
        }
    
        public void Dispose()
        {
            OnDispose();
        }
    }
    

提交回复
热议问题