.net 自定义AOP,透明代理与真实代理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting;
using NewAop;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Services;
using System.ServiceModel;
using System.Runtime.Serialization; namespace NewAop
{ /// <summary>
/// IAopOperator AOP操作符接口,包括前处理和后处理
/// </summary>
public interface IAopOperator
{
void PreProcess(IMessage requestMsg);
void PostProcess(IMessage requestMsg, IMessage Respond);
}
/// <summary>
/// MethodAopSwitcherAttribute 用于决定一个被AopProxyAttribute修饰的class的某个特定方法是否启用截获 。
/// 创建原因:绝大多数时候我们只希望对某个类的一部分Method而不是所有Method使用截获。
/// 使用方法:如果一个方法没有使用MethodAopSwitcherAttribute特性或使用MethodAopSwitcherAttribute(false)修饰,
/// 都不会对其进行截获。只对使用了MethodAopSwitcherAttribute(true)启用截获。
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true,Inherited =true)]
public class MethodAopSwitcherAttribute : Attribute
{
private int useAspect = ; //记录类型
private string userlog = ""; //记录详细信息
public MethodAopSwitcherAttribute(int useAop=, string log="")
{
this.useAspect = useAop;
this.userlog = log;
} public int UseAspect
{
get
{
return this.useAspect;
}
}
public string Userlog
{
get
{
return this.userlog;
}
}
}
/// <summary>
/// IAopProxyFactory 用于创建特定的Aop代理的实例,IAopProxyFactory的作用是使AopProxyAttribute独立于具体的AOP代理类。
/// </summary>
public interface IAopProxyFactory
{
AopProxyBase CreateAopProxyInstance(MarshalByRefObject obj, Type type);
}
/// <summary>
/// AopProxyBase 抽象类 所有自定义AOP代理类都从此类派生,覆写IAopOperator接口,实现具体的前/后处理 。
/// </summary>
public abstract class AopProxyBase : RealProxy, IAopOperator
{
public readonly MarshalByRefObject target; //默认透明代理 #region IAopOperator 成员(两个方法 一个在执行之前调用,另一个在执行之后调用,具体实现代码写在AopControlProxy类中)
public abstract void PreProcess(IMessage requestMsg); //方法执行的预处理逻辑
public abstract void PostProcess(IMessage requestMsg, IMessage Respond); //方法执行结束的处理逻辑
#endregion public AopProxyBase(MarshalByRefObject obj, Type type)
: base(type)
{
this.target = obj;
} #region Invoke 重写基方法
public abstract override IMessage Invoke(IMessage msg); #endregion
}
/// <summary>
/// AopProxyAttribute
/// AOP代理特性,如果一个类想实现具体的AOP,只要实现AopProxyBase和IAopProxyFactory,然后加上该特性即可。
/// </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 创建实例
/// <summary>
/// 获得目标对象的自定义透明代理
/// </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
}
public class AopControlProxyFactory : IAopProxyFactory
{
#region IAopProxyFactory 成员
public AopProxyBase CreateAopProxyInstance(MarshalByRefObject obj, Type type)
{
return new AopControlProxy(obj, type);
}
#endregion
}
public class AopControlProxy : AopProxyBase
{
public AopControlProxy(MarshalByRefObject obj, Type type)
: base(obj, type) //指定调用基类中的构造函数
{
} public override void PreProcess(IMessage requestMsg)
{ Console.WriteLine("目标方法运行开始之前");
return;
} public override void PostProcess(IMessage requestMsg, IMessage Respond)
{
Console.WriteLine("目标方法运行结束之后");
}
public override IMessage Invoke(IMessage msg)
{
int useAspect = ;
string uselog = "";
IMethodCallMessage call = (IMethodCallMessage)msg; //查询目标方法是否使用了启用AOP的MethodAopSwitcherAttribute
foreach (Attribute attr in call.MethodBase.GetCustomAttributes(true))
{
MethodAopSwitcherAttribute mehodAopAttr = attr as MethodAopSwitcherAttribute;
if (mehodAopAttr != null)
{
useAspect = mehodAopAttr.UseAspect;
uselog = mehodAopAttr.Userlog; } if (useAspect == )
{
IMethodCallMessage callMsg = msg as IMethodCallMessage;
this.PostProcess(msg, callMsg); //执行方法之前的操作
}
if (useAspect == )
{
this.PreProcess(msg); //执行方法之前的操作
}
} #region 如果触发的是构造函数,此时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);
}
#endregion #region 调用目标方法代码
IMethodMessage result_msg;
result_msg = RemotingServices.ExecuteMessage(this.target, call);
#endregion //执行方法结束后的操作
this.PostProcess(msg, result_msg);
return result_msg; }
} public interface IExameplec
{ void say_hello(); void sayByeBye(); }
public class ExameplecProxy : IExameplec
{
public IExameplec exp { get; set; }
public ExameplecProxy(string a)
{
exp = new Exameplec(a);
} public void say_hello()
{
var t = Convert.ChangeType(exp, exp.GetType());
(t as dynamic).say_hello();
//((Exameplec)exp).say_hello();
}
public void sayByeBye()
{
exp.sayByeBye();
}
}
//如果在类上添加该代码 会导致没有添加属性的代码也会被带入Invoke中
//导致其他方法执行IMethodCallMessage callMsg = msg as IMethodCallMessage; return new ReturnMessage(callMsg.InArgs, null, 0, null, callMsg);
//最终导致其他方法的代码无法运行
[AopProxyAttribute(typeof(AopControlProxyFactory))] //将自己委托给AOP代理AopControlProxy,(最好不要添加该代码)
public partial class Exameplec : ContextBoundObject, IExameplec// //放到特定的上下文中,该上下文外部才会得到该对象的透明代理
{ private string name;
public Exameplec()
{ } public Exameplec(string a)
{
var t = this.GetType().GetMethod("say_hello").GetCustomAttributes(true)[] as MethodAopSwitcherAttribute;
this.name = a;
}
[MethodAopSwitcher(, "参数1")]
//[MethodAopSwitcher(2, "参数2")]
public void say_hello()
{
Console.WriteLine("say hello");
}
public void sayByeBye()
{
Console.WriteLine("say good bye");
}
} class Program
{
static void Main(string[] args)
{ ExameplecProxy epc = new ExameplecProxy("添加代理的方法");
epc.say_hello();
Console.WriteLine("");
Console.WriteLine("--------------------------这是分隔符--------------------------------"); //Exameplec epcs = new Exameplec("未添加代理的方法");
//epcs.sayByeBye();
//Console.WriteLine("--------------------------这是分隔符--------------------------------"); //Console.ReadLine();
}
}
}
.net 自定义AOP,透明代理与真实代理的更多相关文章
- .net 真实代理和透明代理的交互
.本地代理调用 using System; using System.Runtime.Remoting ; using System.Runtime.Remoting.Services ; using ...
- 何为代理?jdk动态代理与cglib代理、spring Aop代理原理浅析
原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...
- jdk动态代理与cglib代理、spring Aop代理原理-代理使用浅析
原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...
- spring源码系列8:AOP源码解析之代理的创建
回顾 首先回顾: JDK动态代理与CGLIB动态代理 Spring中的InstantiationAwareBeanPostProcessor和BeanPostProcessor的区别 我们得知 JDK ...
- nginx正向代理,反向代理,透明代理(总结)
1正向代理 正向代理,也就是传说中的代理,他的工作原理就像一个跳板, 简单的说, 我是一个用户,我访问不了某网站,但是我能访问一个代理服务器 这个代理服务器呢,他能访问那个我不能访问的网站 于是我先连 ...
- jdk动态代理与cglib代理、spring aop代理实现原理
原创声明:本博客来源与本人另一博客[http://blog.csdn.net/liaohaojian/article/details/63683317]原创作品,绝非他处摘取 代理(proxy)的定义 ...
- jdk动态代理与cglib代理、spring aop代理实现原理解析
原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...
- java中代理,静态代理,动态代理以及spring aop代理方式,实现原理统一汇总
若代理类在程序运行前就已经存在,那么这种代理方式被成为 静态代理 ,这种情况下的代理类通常都是我们在Java代码中定义的. 通常情况下, 静态代理中的代理类和委托类会实现同一接口或是派生自相同的父类. ...
- (大型网站之Nginx)图解正向代理、反向代理、透明代理
一.正向代理(Forward Proxy) 一般情况下,如果没有特别说明,代理技术默认说的是正向代理技术.关于正向代理的概念如下: 正向代理(forward)是一个位于客户端[用户A]和原始服务器(o ...
随机推荐
- golang的sync包例子
package main import ( "fmt" "sync" ) var wg sync.WaitGroup func asyncTestFunc() ...
- vim 编辑技巧
vi是linux下最常用的编辑器,vim是vi的加强版,本篇将介绍vim的一些快捷键和使用技巧,借鉴网上其他文章表示
- "==" 与 “equals”
“==”: “==”或等号操作在Java编程语言中是一个二元操作符,用于比较原生类型和对象.(操作符不支持重载overloading) “==”对比两个对象基于内存引用,如果两个对象的引用完全相同(指 ...
- Vue.js: temple
ylbtech-Vue.js: temple 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 6.返回顶部 7.返回顶部 8.返回顶部 9.返 ...
- 第六章 hbase shell 命令
hbase shell命令 描述 alter 修改列族(Column Family)模式 count 统计表中行的数量 create 创建表 ...
- Code blocks调试教程
特别声明:本教程已转移至百度经验:https://jingyan.baidu.com/article/6b182309939a87ba58e159bf.html 一.题外话 之前一直想用Code bl ...
- OpenCV for Python常用命令
读取图像首先要导入OpenCV包 import cv2 OpenCV目前支持读取bmp.jpg.png.tiff等常用格式. //读取图片 img2 = cv2.imread('out-0022. ...
- 浏览器发起Get,Post请求时候传递的参数编码问题
浏览器发起Get,Post请求时候传递的参数编码问题 最近开发一个网站的时候,用了很多ajax方法,在页面发起Get,post请求,中间自然捎带有很多参数,有中文,有英文,英文一般是不存在编码问题的, ...
- EntityFramework 常见用法汇总
1.Code First 启用存储过程映射实体 1 protected override void OnModelCreating(DbModelBuilder modelBuilder) 2 { 3 ...
- django第一课大概了解
项目目录介绍: -------- manage.py : Django项目里面的工具,通过它可以调用django shell和数据库等. mysite/ 主要是项目配置的信息,通常一次生成后不需要其他 ...