C# AOP微型框架实现(二)

3. AopProxyAttribute AOP代理特性

/****************************** AopProxyAttribute ************************************

using System;
using System.Runtime.Remoting ;
using System.Runtime.Remoting.Proxies ;

namespace EnterpriseServerBase.Aop
{
///

1<summary>   
2/// AopProxyAttribute   
3/// AOP代理特性,如果一个类想实现具体的AOP,只要实现AopProxyBase和IAopProxyFactory,然后加上该特性即可。   
4/// 2005.04.11   
5/// </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
///

1<summary>   
2/// 获得目标对象的自定义透明代理   
3/// </summary>

public override MarshalByRefObject CreateInstance(Type serverType)//serverType是被AopProxyAttribute修饰的类
{
//未初始化的实例的默认透明代理
MarshalByRefObject target = base.CreateInstance (serverType); //得到位初始化的实例(ctor未执行)
object[] args = {target ,serverType} ;
//AopProxyBase rp = (AopProxyBase)Activator.CreateInstance(this.realProxyType ,args) ; //Activator.CreateInstance在调用ctor时通过了代理,所以此处将会失败

//得到自定义的真实代理
AopProxyBase rp = this.proxyFactory.CreateAopProxyInstance(target ,serverType) ;//new AopControlProxy(target ,serverType) ;
return (MarshalByRefObject)rp.GetTransparentProxy() ;
}
#endregion
}
}

4 .MethodAopSwitcherAttribute.cs

/**************************** MethodAopSwitcherAttribute.cs *************************

using System;

namespace EnterpriseServerBase.Aop
{
///

1<summary>   
2/// MethodAopSwitcherAttribute 用于决定一个被AopProxyAttribute修饰的class的某个特定方法是否启用截获 。   
3/// 创建原因:绝大多数时候我们只希望对某个类的一部分Method而不是所有Method使用截获。   
4/// 使用方法:如果一个方法没有使用MethodAopSwitcherAttribute特性或使用MethodAopSwitcherAttribute(false)修饰,   
5/// 都不会对其进行截获。只对使用了MethodAopSwitcherAttribute(true)启用截获。   
6/// 2005.05.11   
7/// </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 ;
}
}
}
}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus