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

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

    The following helper allows to call void and non-void methods. Usage:

    var calculator = new WcfInvoker(() => new CalculatorClient());
    var sum = calculator.Invoke(c => c.Sum(42, 42));
    calculator.Invoke(c => c.RebootComputer());
    

    The class itself is:

    public class WcfInvoker
        where TService : ICommunicationObject
    {
        readonly Func _clientFactory;
    
        public WcfInvoker(Func clientFactory)
        {
            _clientFactory = clientFactory;
        }
    
        public T Invoke(Func action)
        {
            var client = _clientFactory();
            try
            {
                var result = action(client);
                client.Close();
                return result;
            }
            catch
            {
                client.Abort();
                throw;
            }
        }
    
        public void Invoke(Action action)
        {
            Invoke(client =>
            {
                action(client);
                return null;
            });
        }
    }
    
        

    提交回复
    热议问题