AOP(.NET)

Attribute活用

Attribute自作

using System.Runtime.Remoting.Contexts;

using System.Runtime.Remoting.Messaging;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]

public sealed class MyInterceptorAttribute

: ContextAttribute, IContributeObjectSink

{

public MyInterceptorAttribute()

: base("MyInterceptor") { }

// IContributeObjectSinkのメソッド実装

public IMessageSink GetObjectSink(

MarshalByRefObject obj, IMessageSink next)

{

return new MyAopHandler(next);

}

}

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]

public sealed class MyInterceptorMethodAttribute : Attribute { }

AOPコア

public class MyAopHandler : IMessageSink

{

private IMessageSink nextSink;

public IMessageSink NextSink

{

get { return this.nextSink; }

}

public MyAopHandler(IMessageSink nextSink)

{

this.nextSink = nextSink;

}

// 同期

public IMessage SyncProcessMessage(IMessage msg)

{

IMessage retMsg = null;

IMethodCallMessage call = msg as IMethodCallMessage;

if (call == null || (Attribute.GetCustomAttribute(call.MethodBase, typeof(MyInterceptorMethodAttribute))) == null)

{

retMsg = this.nextSink.SyncProcessMessage(msg);

}

else

{

Console.WriteLine("before");

retMsg = this.nextSink.SyncProcessMessage(msg);

Console.WriteLine("after");

}

return retMsg;

}

// 非同期

public IMessageCtrl AsyncProcessMessage(

IMessage msg, IMessageSink replySink)

{

return null;

}

}

利用側

[MyInterceptor]

public class BusinessHandler : ContextBoundObject

{

[MyInterceptorMethod]

public void DoSomething()

{

Console.WriteLine("test");

}

}

var handler = new BusinessHandler();

handler.DoSomething();