我有一个 WCF 服务,它记录所有异常,然后将它们作为 FaultExceptions 抛出。
我正在做很多重复,例如在每个服务方法中。
try {
// do some work
}
catch(Exception ex)
{
Logger.log(ex);
// actually will be Fault Exception but you get the idea.
throw ex;
}
我正在寻找一种更优雅的方法来执行此操作,因为我在每个服务中剪切和粘贴 try/catch。
是否有设计模式/C# 技巧可用于使其更优雅?
最佳答案
你在谈论 AOP - Aspect Oriented Programming
这是我通过将“工作”作为 lambda 传递来实现的方法:
public partial static class Aspect
{
public static T HandleFaultException<T>( Func<T> fn )
{
try
{
return fn();
}
catch( FaultException ex )
{
Logger.log(ex);
throw;
}
}
}
然后使用它:
return Aspect.HandleFaultException( () =>
{
// call WCF
}
);
还有其他方法可以实现相同的目标,甚至还有一些商业产品,但我发现这种方式是最明确和最灵活的。
例如,您可以编写一个切面来为您创建和配置客户端:
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( ... );
}
);
然后,您可以包装您通常想要应用的所有方面并创建一个主方面。
关于c# - 重复代码位的设计模式/C#技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15203331/