Call a WCF service using the extension method

I wrote an extension method for use with WCF services that stores all the logic for removing and handling exceptions in one place. The method is as follows:

public static TResult CallMethod<TChannel, TResult>(
    this ClientBase<TChannel> proxy,
    Func<TResult> func) where TChannel : class
{
    proxy.ThrowIfNull("proxy");
    func.ThrowIfNull("func");

    try
    {
        // set client credentials
        return func();
    }
    finally
    {
        if (proxy != null)
        {
            try
            {
                if (proxy.State != CommunicationState.Faulted)
                {
                    proxy.Close();
                }
                else
                {
                    proxy.Abort();
                }
            }
            catch (CommunicationException)
            {
                proxy.Abort();
            }
            catch (TimeoutException)
            {
                proxy.Abort();
            }
            catch (Exception)
            {
                proxy.Abort();
                throw;
            }
        }
    }
}

The method will be used as follows:

public int CreateBusinessObject(BusinessObject item)
{
    MyServiceClient proxy = new MyServiceClient();
    return proxy.CallMethod(() => proxy.CreateBusinessObject(item));
}

My question is, would it be better than a static method creating a service proxy? I am a little worried about my current implementation. Should building a proxy inside try / catch? My real understanding is that if the constructor fails, nothing is worth it anyway.

+3
source share
1 answer

, . .

, , :

class Program
{
    static void Main(string[] args)
    {
        using (new TestClass())
        {
            Console.WriteLine("In using");
        }
    }

    class TestClass : IDisposable
    {
        public TestClass()
        {
            throw new Exception();
        }

        public void Dispose()
        {
            Console.WriteLine("Disposed");
        }
    }
}

Disposing . , , .

+2

Source: https://habr.com/ru/post/1770490/


All Articles