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

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

    I referred few answers on this post and customized it as per my needs.

    I wanted the ability to do something with WCF client before using it so the DoSomethingWithClient() method.

    public interface IServiceClientFactory
    {
        T DoSomethingWithClient();
    }
    public partial class ServiceClient : IServiceClientFactory
    {
        public ServiceClient DoSomethingWithClient()
        {
            var client = this;
            // do somthing here as set client credentials, etc.
            //client.ClientCredentials = ... ;
            return client;
        }
    }
    

    Here is the helper class:

    public static class Service
        where TClient : class, ICommunicationObject, IServiceClientFactory, new()
    {
        public static TReturn Use(Func codeBlock)
        {
            TClient client = default(TClient);
            bool success = false;
            try
            {
                client = new TClient().DoSomethingWithClient();
                TReturn result = codeBlock(client);
                client.Close();
                success = true;
                return result;
            }
            finally
            {
                if (!success && client != null)
                {
                    client.Abort();
                }
            }
        }
    }
    

    And I can use it as:

    string data = Service.Use(x => x.GetData(7));
    

提交回复
热议问题