设计模式/ C#伎俩为code重复位伎俩、模式、code

2023-09-03 06:22:10 作者:悦风

我有记录的任何异常WCF服务,然后抛出它们作为FaultExceptions。

I have a WCF service which logs any exceptions and then throws them as FaultExceptions.

我做了很多重复例如在每个服务方法。

I am doing a lot of repetition e.g. in each service method.

try { 
   // do some work

}
catch(Exception ex)
{
  Logger.log(ex);

  // actually will be Fault Exception but you get the idea.
  throw ex;
}

我要寻找一个更优雅的方式在整个每项服务做到这一点,因为我剪切和粘贴的try / catch。

I am looking for a more elegant way to do this as I am cutting and pasting the try/catch throughout each service.

有没有一种设计模式/ C#伎俩,可以用来使这更优雅?

Is there a design pattern /C# trick that could be used to make this more elegant?

推荐答案

你说的是AOP - 面向方面编程

You're talking about AOP - Aspect Oriented Programming

下面是我如何做到这一点通过将工作作为一个lambda:

Here's how I do it by passing the "work" as a lambda:

public partial static class Aspect
{
  public static T HandleFaultException<T>( Func<T> fn )
  {
    try
    { 
      return fn();
    }
    catch( FaultException ex )
    {
      Logger.log(ex);
      throw;
    }
  }
}

然后使用它:

Then to use it:

return Aspect.HandleFaultException( () =>
  {
    // call WCF
  }
);

有其他的方法来达到同样的目标,甚至一些商业产品,但我觉得这种方式是最明确和灵活的。

There are other ways to achieve the same goal, and even some commercial products, but I find this way to be the most explicit and flexible.

例如,您可以编写创建和部署客户端为你一个方面:

For example, you can write an aspect that creates and disposes the client for you:

public partial static class Aspect
{
  public static T CallClient<T>( Func<Client, T> fn )
  {
    using ( var client = ... create client ... )
    {
      return fn( client );
    }
  }
}

return Aspect.CallClient( client =>
  {
    return client.Method( ... );
  }
);

然后,你可以用你通常要应用,创造一个主方面的问题。

And then, you can wrap all the aspects you normally want to apply and create one master aspect.