C#實(shí)現(xiàn)AOP微型框架基礎(chǔ)分析
在向大家詳細(xì)介紹C#實(shí)現(xiàn)AOP微型框架之前,首先讓大家了解下微型框架的.cs文件,然后全面介紹C#實(shí)現(xiàn)AOP微型框架。
在前面的系列文章中,我介紹了消息、代理與AOP的關(guān)系,這次將我自己用C#實(shí)現(xiàn)AOP微型框架拿出來(lái)和大家交流一下。
AOP的最基本功能就是實(shí)現(xiàn)特定的預(yù)處理和后處理,我通過(guò)代理讓C#實(shí)現(xiàn)AOP微型框架。先來(lái)看看構(gòu)成此微型框架的.cs文件。
1. AopProxyAttribute AOP代理特性
- using System;
- using System.Runtime.Remoting ;
- using System.Runtime.Remoting.Proxies ;
- namespace EnterpriseServerBase.Aop
- {
- /// <summary>
- /// AopProxyAttribute
- /// AOP代理特性,如果一個(gè)類(lèi)想實(shí)現(xiàn)具體的AOP,
只要實(shí)現(xiàn)AopProxyBase和IAopProxyFactory,然后加上該特性即可。- /// 2005.04.11
- /// </summary>
- [AttributeUsage(AttributeTargets.Class ,AllowMultiple = false)]
- public class AopProxyAttribute : ProxyAttribute
- {
- private IAopProxyFactory proxyFactory = null ;
- public AopProxyAttribute(Type factoryType)
- {
- this.proxyFactory = (IAopProxyFactory)Activator.CreateInstance(factoryType) ;
- }
- #region CreateInstance
- /// <summary>
- /// 獲得目標(biāo)對(duì)象的自定義透明代理
- /// </summary>
- public override MarshalByRefObject CreateInstance(Type serverType)
- //serverType是被AopProxyAttribute修飾的類(lèi)
- {
- //未初始化的實(shí)例的默認(rèn)透明代理
- MarshalByRefObject target = base.CreateInstance (serverType);
- //得到位初始化的實(shí)例(ctor未執(zhí)行)
- object[] args = {target ,serverType} ;
- //AopProxyBase rp = (AopProxyBase)Activator.CreateInstance(this.realProxyType ,args) ;
- //Activator.CreateInstance在調(diào)用ctor時(shí)通過(guò)了代理,所以此處將會(huì)失敗
- //得到自定義的真實(shí)代理
- AopProxyBase rp = this.proxyFactory.CreateAopProxyInstance(target ,serverType) ;
- //new AopControlProxy(target ,serverType) ;
- return (MarshalByRefObject)rp.GetTransparentProxy() ;
- }
- #endregion
- }
- }
2 .MethodAopSwitcherAttribute.cs
- using System;
- namespace EnterpriseServerBase.Aop
- {
- /// <summary>
- /// MethodAopSwitcherAttribute
用于決定一個(gè)被AopProxyAttribute修飾的class的某個(gè)特定方法是否啟用截獲 。- /// 創(chuàng)建原因:絕大多數(shù)時(shí)候我們只希望對(duì)某個(gè)類(lèi)的一部分Method而不是所有Method使用截獲。
- /// 使用方法:如果一個(gè)方法沒(méi)有使用MethodAopSwitcherAttribute
特性或使用MethodAopSwitcherAttribute(false)修飾,- /// 都不會(huì)對(duì)其進(jìn)行截獲。只對(duì)使用了MethodAopSwitcherAttribute(true)啟用截獲。
- /// 2005.05.11
- /// </summary>
- [AttributeUsage(AttributeTargets.Method ,AllowMultiple = false )]
- public class MethodAopSwitcherAttribute : Attribute
- {
- private bool useAspect = false ;
- public MethodAopSwitcherAttribute(bool useAop)
- {
- this.useAspect = useAop ;
- }
- public bool UseAspect
- {
- get
- {
- return this.useAspect ;
- }
- }
- }
- }
【編輯推薦】