这几天在公司,因为业务上的需求,需要对以前写的用例都添加一些初始化操作,由于测试用例非常多,直接添加非常耗时耗力,所以我们使用了一个简单的消息拦截的方法,让以前代码不用进行大规模修改。
消息拦截需要用到的类有ContextAttribute、ContextBoundObject以及两个接口IContributeObjectSink和IMessageSink。
关于AOP以及以上使用到的类与接口,可以看下其他人的介绍:(本人mark)
ContextAttribute与ContextBoundObject应用开发
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;
namespace ConsoleApplication51
{
class MyAOPAttribute : ContextAttribute,IContributeObjectSink
{
public MyAOPAttribute()
: base("MyAOP")
{
}
public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
{
return new MessageSink(nextSink);
}
}
class MessageSink : IMessageSink
{
public MessageSink(IMessageSink messageSink)
{
nextSink = messageSink;
}
private IMessageSink nextSink = null;
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
return null;
}
public IMessageSink NextSink
{
get { return nextSink; }
}
public IMessage SyncProcessMessage(IMessage msg)
{
Console.WriteLine("AOP Call Begin");
IMessage returnMsg = nextSink.SyncProcessMessage(msg);
Console.WriteLine("AOP Call End");
return returnMsg;
}
}
}
下面是主函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication51
{
[MyAOP]
class TestClassContext : ContextBoundObject
{
public void Print()
{
Console.WriteLine("Print");
}
}
class Program
{
static void Main(string[] args)
{
TestClassContext test1 = new TestClassContext();
test1.Print();
/*Output
* AOP Call Begin
* AOP Call End
*/
}
}
}