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

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

    I'd like to add implementation of Service from Marc Gravell's answer for case of using ServiceClient instead of ChannelFactory.

    public interface IServiceConnector
    {
        void Connect(Action clientUsage);
        TResult Connect(Func channelUsage);
    }
    
    internal class ServiceConnector : IServiceConnector
        where TServiceInterface : class where TService : ClientBase, TServiceInterface, new()
    {
        public TResult Connect(Func channelUsage)
        {
            var result = default(TResult);
            Connect(channel =>
            {
                result = channelUsage(channel);
            });
            return result;
        }
    
        public void Connect(Action clientUsage)
        {
            if (clientUsage == null)
            {
                throw new ArgumentNullException("clientUsage");
            }
            var isChanneldClosed = false;
            var client = new TService();
            try
            {
                clientUsage(client);
                client.Close();
                isChanneldClosed = true;
            }
            finally
            {
                if (!isChanneldClosed)
                {
                    client.Abort();
                }
            }
        }
    }
    

提交回复
热议问题