属性でインターセプトの対象を示す
usingしておきます。
using Ninject; using Ninject.Extensions.Interception; using Ninject.Extensions.Interception.Attributes; using Ninject.Extensions.Interception.Infrastructure.Language; using Ninject.Extensions.Interception.Request;
インターセプター。
public class TraceInterceptor : SimpleInterceptor { protected override void BeforeInvoke(IInvocation invocation) { Console.WriteLine("Before"); } protected override void AfterInvoke(IInvocation invocation) { Console.WriteLine("After"); } }
属性はInterceptAttributeを継承して作ります。
public class TraceAttribute : InterceptAttribute { public override IInterceptor CreateInterceptor(IProxyRequest request) { return request.Context.Kernel.Get<TraceInterceptor>(); } }
属性をクラスにつけます。メソッドにもつけられます。
[Trace] public class Person { public virtual void SayHello(string name) { Console.WriteLine("Hello {0}", name); } public virtual void SayGoodbye(string name) { Console.WriteLine("Good bye {0}", name); } }
セットアップと実行。
[global::Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod] public void TraceAttributeTest() { var kernel = new StandardKernel(new NinjectSettings { LoadExtensions = false}, new DynamicProxy2Module()); kernel.Bind<Person>().ToSelf(); var p = kernel.Get<Person>(); p.SayHello("aaa"); p.SayGoodbye("bbb"); }
実行結果。
Before Hello aaa After Before Good bye bbb After
Personのメソッド実行時にインターセプタが動いていることが確認できます。