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

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

    A wrapper like this would work:

    public class ServiceClientWrapper : IDisposable
    {
        private ServiceType _channel;
        public ServiceType Channel
        {
            get { return _channel; }
        }
    
        private static ChannelFactory _channelFactory;
    
        public ServiceClientWrapper()
        {
            if(_channelFactory == null)
                 // Given that the endpoint name is the same as FullName of contract.
                _channelFactory = new ChannelFactory(typeof(T).FullName);
            _channel = _channelFactory.CreateChannel();
            ((IChannel)_channel).Open();
        }
    
        public void Dispose()
        {
            try
            {
                ((IChannel)_channel).Close();
            }
            catch (Exception e)
            {
                ((IChannel)_channel).Abort();
                // TODO: Insert logging
            }
        }
    }
    

    That should enable you to write code like:

    ResponseType response = null;
    using(var clientWrapper = new ServiceClientWrapper())
    {
        var request = ...
        response = clientWrapper.Channel.MyServiceCall(request);
    }
    // Use your response object.
    

    The wrapper could of course catch more exceptions if that is required, but the principle remains the same.

提交回复
热议问题