使用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