简体   繁体   English

使用扩展方法调用WCF服务

[英]Calling WCF service using extension method

I've written an extension method for use with WCF services that keeps all the disposal and exception handling logic in one place. 我编写了一个与WCF服务一起使用的扩展方法,它将所有处理和异常处理逻辑保存在一个地方。 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 like this: 该方法将使用如下:

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

My question really is whether this would be better as a static method which creates the service proxy? 我的问题是,这是否会更好地作为创建服务代理的静态方法? I'm slightly worried about my current implementation. 我有点担心我目前的实施情况。 Should the construction of the proxy be inside the try/catch? 代理的构造是否应该在try / catch中? My current understanding is that if the constructor fails, there is nothing to dispose of anyway. 我目前的理解是,如果构造函数失败,无论如何都没有什么可以处理的。

If the constructor fails, the entire object is in an invalid state. 如果构造函数失败,则整个对象处于无效状态。 You should not be worried about disposing in this case. 你不应该担心在这种情况下处置。

A nice test for this is what would happen when you execute the following: 对此执行的一个很好的测试是执行以下操作时会发生什么:

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");
        }
    }
}

The result is that the Disposing never gets reached. 结果是永远不会达到处置。 This is what happens when the constructor fails. 这是构造函数失败时发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM