1つ前の記事で、メソッド呼び出しの前後にログを挟み込むPIABの使い方を試してみた。
今回は、あり合わせのHandlerじゃなくて、独自のHandlerを作ってみようと思う。
前回のプロジェクトにクラスライブラリのプロジェクトを1つ追加する。
名前はMyHandlersにした。
MyHandlersプロジェクトに以下の参照を追加する。
- Enterprise Library Policy Injection Application Block
- Enterprise Library Shared Library
- Microsoft.Practices.Unity
- Microsoft.Practices.Unity.InterceptionExtension
- Microsoft.Practices.ObjectBuilder2
- System.Configuration
Unity関連の3つの参照は、PIABSampleAppのほうにも追加しておく。
PIABのカスタムハンドラをここに作成していく。カスタムハンドラになるためには、最低限以下の条件を満たしてないといけないみたい。
- Microsoft.Practices.Unity.InterceptionExtension.ICallHandlerを実装する
- [ConfigurationElementType(typeof(CustomCallHandlerData))]属性がついている
- NameValueCollectionを受け取るコンストラクタがある
ということで実装開始。とりあえず、メソッド呼び出しの前後に標準出力にメッセージをだすようにしてみた。
using System;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace MyHandlers
{
[ConfigurationElementType(typeof(CustomCallHandlerData))]
public class MyHandler : ICallHandler
{
// このコンストラクタ必須!
public MyHandler(NameValueCollection attributes) { }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
// 本来の処理の呼び出しの前後に、クラス名とメソッド名を出力する
var name = input.Target.GetType() + "." + input.MethodBase.Name;
Console.WriteLine("Before: " + name);
try
{
return getNext().Invoke(input, getNext);
}
finally
{
Console.WriteLine("After: " + name);
}
}
public int Order { get; set; }
}
}
PIABSampleAppの参照に、今作成したMyHandlersを追加する。そして、App.configを以下のように構成する。
前のサンプルで作っていたLogging Handlerを削除して、かわりにCustom Handlerを追加する。
Custom HandlerのTypeにMyHandlers.MyHandlerを設定する。
Typeプロパティの横のボタンを押して、Handlerを選択するためのダイアログを表示する。そして、MyHandlers.dllを開く。そうするとMyHandlerが選択できるので選択してOKをクリックする。
TypeにMyHandlerが設定される。
これで、実行すると下のような実行結果になる。自作のHandlerが効いてるのがわかると思う。
実行結果
Before: PIABSampleApp.Target.Greet
Target.Greet Called.
After: PIABSampleApp.Target.Greet