Tuesday, January 19, 2010

WCF Client wrapper

The using statment and WCF are a bad combo.. Instead use the following class. With some lambda together with this class it's almost like a using statement.

 using System;
    using System;
    using System.ServiceModel;

    /// 
    /// Helper class for WCF clients
    /// 
    public class WcfClientUtils
    {
        /// 
        /// Execute actions against the client and aborts the client on a faulted state
        /// 
        /// Client type
        /// Client instance
        /// Actions to perform on instance
        /// 
        /// WcfClientUtils.Execute(new ServiceReference1.Service1Client(),
        ///     client =>
        ///     {
        ///         var returnData = client.HelloWorld());
        ///     });
        /// 
        public static void Execute(T client, Action action) where T : ICommunicationObject
        {
            try
            {
                //client.Open();
                action(client);
                client.Close();
            }
            catch (CommunicationException)
            {
                client.Abort();
                throw;
            }
            catch (TimeoutException)
            {
                client.Abort();
                throw;
            }
            catch (Exception)
            {
                if (client.State == CommunicationState.Faulted)
                {
                    client.Abort();
                }

                throw;
            }
        }
    }

And this is how you could use this class

WcfClientUtils.Execute(new ServiceReference1.Service1Client(),
    client =>
        {
            var returnData = client.HelloWorld());
});
Share:

0 kommentarer:

Post a Comment