在前面的系列文章中,我介紹了消息、代理與aop的關系,這次將我自己實現的一個aop微型框架拿出來和大家交流一下。
aop的最基本功能就是實現特定的預處理和后處理,我通過代理實現了此微型框架。
先來看看構成此微型框架的4個.cs文件。
1.commondef.cs 用于定義最基本的aop接口
/************************************* commondef.cs **************************
using system;
using system.runtime.remoting.messaging ;
namespace enterpriseserverbase.aop
{
/// <summary>
/// iaopoperator aop操作符接口,包括前處理和后處理
/// 2005.04.12
/// </summary>
public interface iaopoperator
{
void preprocess(imessage requestmsg ) ;
void postprocess(imessage requestmsg ,imessage respond) ;
}
/// <summary>
/// iaopproxyfactory 用于創建特定的aop代理的實例,iaopproxyfactory的作用是使aopproxyattribute獨立于具體的aop代理類。
/// </summary>
public interface iaopproxyfactory
{
aopproxybase createaopproxyinstance(marshalbyrefobject obj ,type type) ;
}
}
2. aopproxybase aop代理的基類,所有自定義aop代理類都從此類派生,覆寫iaopoperator接口,實現具體的前/后處理 。
using system;
using system.runtime.remoting ;
using system.runtime.remoting.proxies ;
using system.runtime.remoting.messaging ;
using system.runtime.remoting.services ;
using system.runtime.remoting.activation ;
namespace enterpriseserverbase.aop
{
/// <summary>
/// aopproxybase 所有自定義aop代理類都從此類派生,覆寫iaopoperator接口,實現具體的前/后處理 。
/// 2005.04.12
/// </summary>
public abstract class aopproxybase : realproxy ,iaopoperator
{
private readonly marshalbyrefobject target ; //默認透明代理
public aopproxybase(marshalbyrefobject obj ,type type) :base(type)
{
this.target = obj ;
}
#region invoke
public override imessage invoke(imessage msg)
{
bool useaspect = false ;
imethodcallmessage call = (imethodcallmessage)msg ;
//查詢目標方法是否使用了啟用aop的methodaopswitcherattribute
foreach(attribute attr in call.methodbase.getcustomattributes(false))
{
methodaopswitcherattribute mehodaopattr = attr as methodaopswitcherattribute ;
if(mehodaopattr != null)
{
if(mehodaopattr.useaspect)
{
useaspect = true ;
break ;
}
}
}
if(useaspect)
{
this.preprocess(msg) ;
}
//如果觸發的是構造函數,此時target的構建還未開始
iconstructioncallmessage ctor = call as iconstructioncallmessage ;
if(ctor != null)
{
//獲取最底層的默認真實代理
realproxy default_proxy = remotingservices.getrealproxy(this.target) ;
default_proxy.initializeserverobject(ctor) ;
marshalbyrefobject tp = (marshalbyrefobject)this.gettransparentproxy() ; //自定義的透明代理 this
return enterpriseserviceshelper.createconstructionreturnmessage(ctor,tp);
}
imethodreturnmessage result_msg = remotingservices.executemessage(this.target ,call) ; //將消息轉化為堆棧,并執行目標方法,方法完成后,再將堆棧轉化為消息
if(useaspect)
{
this.postprocess(msg ,result_msg) ;
}
return result_msg ;
}
#endregion
#region iaopoperator 成員
public abstract void preprocess(imessage requestmsg) ;
public abstract void postprocess(imessage requestmsg, imessage respond) ;
#endregion
}
}
新聞熱點
疑難解答