2

我的应用程序使用 WCF 调用 Web 服务。调用可能因各种原因而失败:

  • 过错
  • 暂停
  • 连接丢失
  • ...

我想记录所有此类错误。我不想将每个调用都包装在 try-catch 中,而是想在一个地方为整个应用程序中的所有 Web 服务调用执行此操作。

不幸的是,IClientMessageInspector 不会因超时和连接失败而被调用。是否有可用于集中记录所有异常的 WCF 扩展点?

请注意,我不只是想将错误记录为 WCF Tracing 之类的文本。我想记录:

  • 服务名称
  • 方法名
  • 期间
  • 异常.ToString()

我愿意接受解决方法。

4

1 回答 1

1

我不知道扩展点,但我可以提供我们使用的解决方法。基本上,我们创建了一个所有服务调用都通过的“代理”。下面是代理及其使用示例。

/// <summary>
/// Proxy for executing generic service methods
/// </summary>
public class ServiceProxy
{
    /// <summary>
    /// Execute service method and get return value
    /// </summary>
    /// <typeparam name="C">Type of service</typeparam>
    /// <typeparam name="T">Type of return value</typeparam>
    /// <param name="action">Delegate for implementing the service method</param>
    /// <returns>Object of type T</returns>
    public static T Execute<C, T>(Func<C, T> action) where C : class, ICommunicationObject, new()
    {
        C svc = null;

        T result = default(T);

        try
        {
            svc = new C();

            result = action.Invoke(svc);

            svc.Close();
        }
        catch (FaultException ex)
        {
            // Logging goes here
            // Service Name: svc.GetType().Name
            // Method Name: action.Method.Name
            // Duration: You could note the time before/after the service call and calculate the difference
            // Exception: ex.Reason.ToString()

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }
        catch (Exception ex)
        {
            // Logging goes here

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }

        return result;
    }
}

及其使用示例:

var result = ServiceProxy.Execute<MyServiceClient, MyReturnType>
(
    svc => svc.GetSomething(someId)
);
于 2012-07-10T16:02:18.183 回答