使用Unity.Interception来清理代码。随着拦截处理,你的代码看起来是这样的:
int f()
{
// no need to try-catch any more, here or anywhere else...
int i = process();
return i;
}
所有你需要在下一步要做的就是定义一个拦截处理程序,它可以对异常处理度身订制。使用这个处理程序,您可以处理在您的应用程序中抛出的所有异常。好处是你不再需要用try-catch块来标记你的所有代码。
public class MyCallHandler : ICallHandler, IDisposable
{
public IMethodReturn Invoke(IMethodInvocation input,
GetNextHandlerDelegate getNext)
{
// call the method
var methodReturn = getNext().Invoke(input, getNext);
// check if an exception was raised.
if (methodReturn.Exception != null)
{
// take the original exception and raise a new (correct) one...
CreateSpecificFault(methodReturn.Exception);
// set the original exception to null to avoid throwing yet another
// exception
methodReturn.Exception = null;
}
// complete the invoke...
return methodReturn;
}
}
向处理程序注册类可以通过配置文件或编程方式完成。代码非常简单。注册后,您实例使用Unity你的对象,像这样:
var objectToUse = myUnityContainer.Resolve<MyObjectToUse>();
更多Unity.Interception:
http://msdn.microsoft.com/en-us/library/ff646991.aspx
相关:[是否有标准的“从不返回”属性的C#函数?](http://stackoverflow.com/questions/1999181/is-there-a-standard-never-returns-attribute-for-c函数) – 2010-10-08 17:42:19