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

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

    public static class Service
    {
        public static ChannelFactory ChannelFactory = new ChannelFactory("*");
    
        public static TReturn Use(Func codeBlock)
        {
            var proxy = (IClientChannel)ChannelFactory.CreateChannel();
            var success = false;
            try
            {
                var result = codeBlock((TChannel)proxy);
                proxy.Close();
                success = true;
                return result;
            }
            finally
            {
                if (!success)
                {
                    proxy.Abort();
                }
            }
        }
    }
    

    So it allows to write return statements nicely:

    return Service.Use(orderService => 
    { 
        return orderService.PlaceOrder(request); 
    }); 
    

提交回复
热议问题