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