C#實現(xiàn)AOP微型框架基礎(chǔ)分析
作者:佚名
這里介紹C#實現(xiàn)AOP微型框架,AOP的最基本功能就是實現(xiàn)特定的預(yù)處理和后處理,我通過代理讓C#實現(xiàn)AOP微型框架。先來看看構(gòu)成此微型框架的.cs文件。
在向大家詳細介紹C#實現(xiàn)AOP微型框架之前,首先讓大家了解下微型框架的.cs文件,然后全面介紹C#實現(xiàn)AOP微型框架。
在前面的系列文章中,我介紹了消息、代理與AOP的關(guān)系,這次將我自己用C#實現(xiàn)AOP微型框架拿出來和大家交流一下。
AOP的最基本功能就是實現(xiàn)特定的預(yù)處理和后處理,我通過代理讓C#實現(xiàn)AOP微型框架。先來看看構(gòu)成此微型框架的.cs文件。
1. AopProxyAttribute AOP代理特性
- using System;
- using System.Runtime.Remoting ;
- using System.Runtime.Remoting.Proxies ;
- namespace EnterpriseServerBase.Aop
- {
- /// <summary>
- /// AopProxyAttribute
- /// AOP代理特性,如果一個類想實現(xiàn)具體的AOP,
只要實現(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>
- /// 獲得目標對象的自定義透明代理
- /// </summary>
- public override MarshalByRefObject CreateInstance(Type serverType)
- //serverType是被AopProxyAttribute修飾的類
- {
- //未初始化的實例的默認透明代理
- MarshalByRefObject target = base.CreateInstance (serverType);
- //得到位初始化的實例(ctor未執(zhí)行)
- object[] args = {target ,serverType} ;
- //AopProxyBase rp = (AopProxyBase)Activator.CreateInstance(this.realProxyType ,args) ;
- //Activator.CreateInstance在調(diào)用ctor時通過了代理,所以此處將會失敗
- //得到自定義的真實代理
- 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
用于決定一個被AopProxyAttribute修飾的class的某個特定方法是否啟用截獲 。- /// 創(chuàng)建原因:絕大多數(shù)時候我們只希望對某個類的一部分Method而不是所有Method使用截獲。
- /// 使用方法:如果一個方法沒有使用MethodAopSwitcherAttribute
特性或使用MethodAopSwitcherAttribute(false)修飾,- /// 都不會對其進行截獲。只對使用了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 ;
- }
- }
- }
- }
【編輯推薦】
責(zé)任編輯:佚名
來源:
博客園