Tuesday 12 April 2022

Custome Service Class to connect wcf service

 using System;

using System.ServiceModel;

namespace Custom.Service.Client
{
    // Borrowed from: http://old.iserviceoriented.com/blog/post/Indisposable+-+WCF+Gotcha+1.aspx
    public static class Service<TServiceClient>
    {
        private static readonly ChannelFactory<TServiceClient> ChannelFactory =
            new ChannelFactory<TServiceClient>(string.Empty);

        public static TResult Use<TResult>(Func<TServiceClient, TResult> action)
        {
            using (var channel = (IClientChannel)ChannelFactory.CreateChannel())
            {
                try
                {
                    return action((TServiceClient)channel);
                }
                finally
                {
                    try
                    {
                        channel.Close();
                    }
                    catch (Exception)
                    {
                        channel.Abort();
                    }
                }
            }
        }

        public static void Use(Action<TServiceClient> action)
        {
            using (var channel = (IClientChannel)ChannelFactory.CreateChannel())
            {
                try
                {
                    action((TServiceClient)channel);
                }
                finally
                {
                    try
                    {
                        channel.Close();
                    }
                    catch (Exception)
                    {
                        channel.Abort();
                    }
                }
            }
        }

        public static IAsyncResult Begin(Func<TServiceClient, IAsyncResult> action)
        {
            TServiceClient channel = ChannelFactory.CreateChannel();
            return action(channel);
        }

        public static TResult End<TResult>(IAsyncResult asyncResult, Func<TServiceClient, TResult> action)
        {
            var channel = (IClientChannel)asyncResult.AsyncState;

            try
            {
                return action((TServiceClient)channel);
            }
            finally
            {
                try
                {
                    channel.Close();
                }
                catch (Exception)
                {
                    channel.Abort();
                }
            }
        }
    }
}

No comments:

Post a Comment

Custome Service Class to connect wcf service

  using  System; using  System.ServiceModel; namespace Custom.Service.Client {      // Borrowed from: http://old.iserviceoriented.com/blog/p...