服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - AOP从静态代理到动态代理(Emit实现)详解

AOP从静态代理到动态代理(Emit实现)详解

2022-03-01 14:14柒小 C#

AOP为Aspect Oriented Programming的缩写,意思是面向切面编程的技术。下面这篇文章主要给大家介绍了关于AOP从静态代理到动态代理(Emit实现)的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

【前言】

aop(aspect orient programming),我们一般称为面向方面(切面)编程,作为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、日志、缓存等等。aop实现的关键在于aop框架自动创建的aop代理,aop代理主要分为静态代理和动态代理,静态代理的代表为aspectj;而动态代理则以spring aop为代表。

何为切面?

一个和业务没有任何耦合相关的代码段,诸如:调用日志,发送邮件,甚至路由分发。一切能为代码所有且能和代码充分解耦的代码都可以作为一个业务代码的切面。

我们为什么要aop?

那我们从一个场景举例说起:

如果想要采集用户操作行为,我们需要掌握用户调用的每一个接口的信息。这时候的我们要怎么做?

如果不采用aop技术,也是最简单的,所有方法体第一句话先调用一个日志接口将方法信息传递记录。

有何问题?

实现业务没有任何问题,但是随之而来的是代码臃肿不堪,难以调整维护的诸多问题(可自行脑补)。

如果我们采用了aop技术,我们就可以在系统启动的地方将所有将要采集日志的类注入,每一次调用方法前,aop框架会自动调用我们的日志代码。

是不是省去了很多重复无用的劳动?代码也将变得非常好维护(有朝一日不需要了,只需将切面代码注释掉即可)

接下来我们看看aop框架的工作原理以及实过程。

【实现思路】

aop框架呢,一般通过静态代理和动态代理两种实现方式。

  AOP从静态代理到动态代理(Emit实现)详解

何为静态代理?

静态代理,又叫编译时代理,就是在编译的时候,已经存在代理类,运行时直接调用的方式。说的通俗一点,就是自己手动写代码实现代理类的方式。

我们通过一个例子来展现一下静态代理的实现过程:

我们这里有一个业务类,里面有方法test(),我们要在test调用前和调用后分别输出日志。

AOP从静态代理到动态代理(Emit实现)详解

我们既然要将log当作一个切面,我们肯定不能去动原有的业务代码,那样也违反了面向对象设计之开闭原则。

那么我们要怎么做呢?我们定义一个新类 businessproxy 去包装一下这个类。为了便于在多个方法的时候区分和辨认,方法也叫 test()

AOP从静态代理到动态代理(Emit实现)详解

这样,我们如果要在所有的business类中的方法都添加log,我们就在businessproxy代理类中添加对应的方法去包装。既不破坏原有逻辑,又可以实现前后日志的功能。

当然,我们可以有更优雅的实现方式:

AOP从静态代理到动态代理(Emit实现)详解

我们可以定义代理类,继承自业务类。将业务类中的方法定义为虚方法。那么我们可以重写父类的方法并且在加入日志以后再调用父类的原方法。

当然,我们还有更加优雅的实现方式:

AOP从静态代理到动态代理(Emit实现)详解

我们可以使用发射的技术,写一个通用的invoke方法,所有的方法都可以通过该方法调用。

我们这样便实现了一个静态代理。

那我们既然有了静态代理,为什么又要有动态代理呢?

我们仔细回顾静态代理的实现过程。我们要在所有的方法中添加切面,我们就要在代理类中重写所有的业务方法。更有甚者,我们有n个业务类,就要定义n个代理类。这是很庞大的工作量。

AOP从静态代理到动态代理(Emit实现)详解

这就是动态代理出现的背景,相比都可以猜得到,动态代理就是将这一系列繁琐的步骤自动化,让程序自动为我们生成代理类。

何为动态代理?

动态代理,又成为运行时代理。在程序运行的过程中,调用了生成代理类的代码,将自动生成业务类的代理类。不需要我们手共编写,极高的提高了工作效率和调整了程序员的心态。

原理不必多说,就是动态生成静态代理的代码。我们要做的,就是选用一种生成代码的方式去生成。

今天我分享一个简单的aop框架,代码使用emit生成。当然,emit 代码的写法不是今天要讲的主要内容,需要提前去学习。

先说效果:

定义一个action特性类 actionattribute继承自 actionbaseattribute,里面在before和after方法中输出两条日志;

AOP从静态代理到动态代理(Emit实现)详解

定义一个action特性类interceptorattribute 继承自interceptorbaseattribute,里面捕获了方法调用异常,以及执行前后分别输出日志;

AOP从静态代理到动态代理(Emit实现)详解

然后定义一个业务类businessclass 实现了ibusinessclass 接口,定义了各种类型的方法

AOP从静态代理到动态代理(Emit实现)详解

AOP从静态代理到动态代理(Emit实现)详解

多余的方法不贴图了。

我们把上面定义的方法调用切面标签放在业务类上,表示该类下所有的方法都执行异常过滤;

我们把action特性放在test方法上,表明要在 test() 方法的 before 和 after 调用时记录日志;

我们定义测试类:

AOP从静态代理到动态代理(Emit实现)详解

调用一下试试:

AOP从静态代理到动态代理(Emit实现)详解

可见,全类方法标签 interceptor 在 test 和 getint 方法调用前后都打出了对应的日志;

action方法标签只在 test 方法上做了标记,那么test方法 before 和 after 执行时打出了日志;

【实现过程】

实现的思路在上面已经有详细的讲解,可以参考静态代理的实现思路。

我们定义一个动态代理生成类 dynamicproxy,用于原业务代码的扫描和代理类代码的生成;

定义两个过滤器标签,actionbaseattribute,提供before和after切面方法;interceptorbaseattribute,提供 invoke “全调用”包装的切面方法;

before可以获取到当前调用的方法和参数列表,after可以获取到当前方法调用以后的结果。

invoke 可以拿到当前调用的对象和方法名,参数列表。在这里进行反射动态调用。

?
1
2
3
4
5
6
7
[attributeusage(attributetargets.method | attributetargets.class, allowmultiple = false, inherited = true)]
 public class actionbaseattribute : attribute
 {
 public virtual void before(string @method, object[] parameters) { }
 
 public virtual object after(string @method, object result) { return result; }
 }
?
1
2
3
4
5
6
7
8
[attributeusage(attributetargets.class, allowmultiple = false, inherited = true)]
 public class interceptorbaseattribute : attribute
 {
 public virtual object invoke(object @object, string @method, object[] parameters)
 {
  return @object.gettype().getmethod(@method).invoke(@object, parameters);
 }
 }

代理生成类采用emit的方式生成运行时il代码。

先把代码放在这里:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
public class dynamicproxy
 {
 public static tinterface createproxyofrealize<tinterface, timp>() where timp : class, new() where tinterface : class
 {
  return invoke<tinterface, timp>();
 }
 
 public static tproxyclass createproxyofinherit<tproxyclass>() where tproxyclass : class, new()
 {
  return invoke<tproxyclass, tproxyclass>(true);
 }
 
 private static tinterface invoke<tinterface, timp>(bool inheritmode = false) where timp : class, new() where tinterface : class
 {
  var imptype = typeof(timp);
 
  string nameofassembly = imptype.name + "proxyassembly";
  string nameofmodule = imptype.name + "proxymodule";
  string nameoftype = imptype.name + "proxy";
 
  var assemblyname = new assemblyname(nameofassembly);
 
  var assembly = appdomain.currentdomain.definedynamicassembly(assemblyname, assemblybuilderaccess.run);
  var modulebuilder = assembly.definedynamicmodule(nameofmodule);
 
  //var assembly = appdomain.currentdomain.definedynamicassembly(assemblyname, assemblybuilderaccess.runandsave);
  //var modulebuilder = assembly.definedynamicmodule(nameofmodule, nameofassembly + ".dll");
 
  typebuilder typebuilder;
  if (inheritmode)
  typebuilder = modulebuilder.definetype(nameoftype, typeattributes.public, imptype);
  else
  typebuilder = modulebuilder.definetype(nameoftype, typeattributes.public, null, new[] { typeof(tinterface) });
 
  injectinterceptor<timp>(typebuilder, imptype.getcustomattribute(typeof(interceptorbaseattribute))?.gettype(), inheritmode);
 
  var t = typebuilder.createtype();
 
  //assembly.save(nameofassembly + ".dll");
 
  return activator.createinstance(t) as tinterface;
 }
 
 private static void injectinterceptor<timp>(typebuilder typebuilder, type interceptorattributetype, bool inheritmode = false)
 {
  var imptype = typeof(timp);
  // ---- define fields ----
  fieldbuilder fieldinterceptor = null;
  if (interceptorattributetype != null)
  {
  fieldinterceptor = typebuilder.definefield("_interceptor", interceptorattributetype, fieldattributes.private);
  }
  // ---- define costructors ----
  if (interceptorattributetype != null)
  {
  var constructorbuilder = typebuilder.defineconstructor(methodattributes.public, callingconventions.standard, null);
  var ilofctor = constructorbuilder.getilgenerator();
 
  ilofctor.emit(opcodes.ldarg_0);
  ilofctor.emit(opcodes.newobj, interceptorattributetype.getconstructor(new type[0]));
  ilofctor.emit(opcodes.stfld, fieldinterceptor);
  ilofctor.emit(opcodes.ret);
  }
 
  // ---- define methods ----
 
  var methodsoftype = imptype.getmethods(bindingflags.public | bindingflags.instance);
 
  string[] ignoremethodname = new[] { "gettype", "tostring", "gethashcode", "equals" };
 
  foreach (var method in methodsoftype)
  {
  //ignore method
  if (ignoremethodname.contains(method.name))
   return;
 
  var methodparametertypes = method.getparameters().select(p => p.parametertype).toarray();
 
  methodattributes methodattributes;
 
  if (inheritmode)
   methodattributes = methodattributes.public | methodattributes.virtual;
  else
   methodattributes = methodattributes.public | methodattributes.hidebysig | methodattributes.newslot | methodattributes.virtual | methodattributes.final;
 
  var methodbuilder = typebuilder.definemethod(method.name, methodattributes, callingconventions.standard, method.returntype, methodparametertypes);
 
  var ilmethod = methodbuilder.getilgenerator();
 
  // set local field
  var impobj = ilmethod.declarelocal(imptype);  //instance of imp object
  var methodname = ilmethod.declarelocal(typeof(string)); //instance of method name
  var parameters = ilmethod.declarelocal(typeof(object[])); //instance of parameters
  var result = ilmethod.declarelocal(typeof(object));  //instance of result
  localbuilder actionattributeobj = null;
 
  //attribute init
  type actionattributetype = null;
  if (method.getcustomattribute(typeof(actionbaseattribute)) != null || imptype.getcustomattribute(typeof(actionbaseattribute)) != null)
  {
   //method can override class attrubute
   if (method.getcustomattribute(typeof(actionbaseattribute)) != null)
   {
   actionattributetype = method.getcustomattribute(typeof(actionbaseattribute)).gettype();
   }
   else if (imptype.getcustomattribute(typeof(actionbaseattribute)) != null)
   {
   actionattributetype = imptype.getcustomattribute(typeof(actionbaseattribute)).gettype();
   }
 
   actionattributeobj = ilmethod.declarelocal(actionattributetype);
   ilmethod.emit(opcodes.newobj, actionattributetype.getconstructor(new type[0]));
   ilmethod.emit(opcodes.stloc, actionattributeobj);
  }
 
  //instance imp
  ilmethod.emit(opcodes.newobj, imptype.getconstructor(new type[0]));
  ilmethod.emit(opcodes.stloc, impobj);
 
  //if no attribute
  if (fieldinterceptor != null || actionattributeobj != null)
  {
   ilmethod.emit(opcodes.ldstr, method.name);
   ilmethod.emit(opcodes.stloc, methodname);
 
   ilmethod.emit(opcodes.ldc_i4, methodparametertypes.length);
   ilmethod.emit(opcodes.newarr, typeof(object));
   ilmethod.emit(opcodes.stloc, parameters);
 
   // build the method parameters
   for (var j = 0; j < methodparametertypes.length; j++)
   {
   ilmethod.emit(opcodes.ldloc, parameters);
   ilmethod.emit(opcodes.ldc_i4, j);
   ilmethod.emit(opcodes.ldarg, j + 1);
   //box
   ilmethod.emit(opcodes.box, methodparametertypes[j]);
   ilmethod.emit(opcodes.stelem_ref);
   }
  }
 
  //dynamic proxy action before
  if (actionattributetype != null)
  {
   //load arguments
   ilmethod.emit(opcodes.ldloc, actionattributeobj);
   ilmethod.emit(opcodes.ldloc, methodname);
   ilmethod.emit(opcodes.ldloc, parameters);
   ilmethod.emit(opcodes.call, actionattributetype.getmethod("before"));
  }
 
  if (interceptorattributetype != null)
  {
   //load arguments
   ilmethod.emit(opcodes.ldarg_0);//this
   ilmethod.emit(opcodes.ldfld, fieldinterceptor);
   ilmethod.emit(opcodes.ldloc, impobj);
   ilmethod.emit(opcodes.ldloc, methodname);
   ilmethod.emit(opcodes.ldloc, parameters);
   // call invoke() method of interceptor
   ilmethod.emit(opcodes.callvirt, interceptorattributetype.getmethod("invoke"));
  }
  else
  {
   //direct call method
   if (method.returntype == typeof(void) && actionattributetype == null)
   {
   ilmethod.emit(opcodes.ldnull);
   }
 
   ilmethod.emit(opcodes.ldloc, impobj);
   for (var j = 0; j < methodparametertypes.length; j++)
   {
   ilmethod.emit(opcodes.ldarg, j + 1);
   }
   ilmethod.emit(opcodes.callvirt, imptype.getmethod(method.name));
   //box
   if (actionattributetype != null)
   {
   if (method.returntype != typeof(void))
    ilmethod.emit(opcodes.box, method.returntype);
   else
    ilmethod.emit(opcodes.ldnull);
   }
  }
 
  //dynamic proxy action after
  if (actionattributetype != null)
  {
   ilmethod.emit(opcodes.stloc, result);
   //load arguments
   ilmethod.emit(opcodes.ldloc, actionattributeobj);
   ilmethod.emit(opcodes.ldloc, methodname);
   ilmethod.emit(opcodes.ldloc, result);
   ilmethod.emit(opcodes.call, actionattributetype.getmethod("after"));
  }
 
  // pop the stack if return void
  if (method.returntype == typeof(void))
  {
   ilmethod.emit(opcodes.pop);
  }
  else
  {
   //unbox,if direct invoke,no box
   if (fieldinterceptor != null || actionattributeobj != null)
   {
   if (method.returntype.isvaluetype)
    ilmethod.emit(opcodes.unbox_any, method.returntype);
   else
    ilmethod.emit(opcodes.castclass, method.returntype);
   }
  }
  // complete
  ilmethod.emit(opcodes.ret);
  }
 }
 }

里面实现了两种代理方式,一种是 面向接口实现 的方式,另一种是 继承重写 的方式。

但是继承重写的方式需要把业务类的所有方法写成virtual虚方法,动态类会重写该方法。

我们从上一节的demo中获取到运行时生成的代理类dll,用ilspy反编译查看源代码:

AOP从静态代理到动态代理(Emit实现)详解

可以看到,我们的代理类分别调用了我们特性标签中的各项方法。

核心代码分析(源代码在上面折叠部位已经贴出):

AOP从静态代理到动态代理(Emit实现)详解

解释:如果该方法存在action标签,那么加载 action 标签实例化对象,加载参数,执行before方法;如果该方法存在interceptor标签,那么使用类字段this._interceptor调用该标签的invoke方法。

AOP从静态代理到动态代理(Emit实现)详解

解释:如果面的interceptor特性标签不存在,那么会加载当前扫描的方法对应的参数,直接调用方法;如果action标签存在,则将刚才调用的结果包装成object对象传递到after方法中。

这里如果目标参数是object类型,而实际参数是直接调用返回的明确的值类型,需要进行装箱操作,否则运行时报调用内存错误异常。

AOP从静态代理到动态代理(Emit实现)详解

解释:如果返回值是void类型,则直接结束并返回结果;如果返回值是值类型,则需要手动拆箱操作,如果是引用类型,那么需要类型转换操作。

il实现的细节,这里不做重点讨论。

【系统测试】  

1.接口实现方式,api测试(各种标签使用方式对应的不同类型的方法调用):

AOP从静态代理到动态代理(Emit实现)详解

结论:对于上述穷举的类型,各种标签使用方式皆成功打出了日志;

2.继承方式,api测试(各种标签使用方式对应的不同类型的方法调用):

AOP从静态代理到动态代理(Emit实现)详解

结论:继承方式和接口实现方式的效果是一样的,只是方法上需要不同的实现调整;

3.直接调用三个方法百万次性能结果:

AOP从静态代理到动态代理(Emit实现)详解

结论:直接调用三个方法百万次调用耗时 58ms

4.使用实现接口方式三个方法百万次调用结果

AOP从静态代理到动态代理(Emit实现)详解

结论:结果见上图,需要注意是三个方法百万次调用,也就是300w次的方法调用

5.使用继承方式三个方法百万次调用结果

AOP从静态代理到动态代理(Emit实现)详解

结论:结果见上图,需要注意是三个方法百万次调用,也就是300w次的方法调用

事实证明,il emit的实现方式性能还是很高的。

综合分析:

通过各种的调用分析,可以看出使用代理以后和原生方法调用相比性能损耗在哪里。性能差距最大的,也是耗时最多的实现方式就是添加了全类方法代理而且是使用invoke进行全方法切面方式。该方式耗时的原因是使用了反射invoke的方法。

直接添加action代理类实现 before和after的方式和原生差距不大,主要损耗在after触发时的拆装箱上。

综上分析,我们使用的时候,尽量针对性地对某一个方法进行aop注入,而尽量不要全类方法进行aop注入。

【总结】

通过自己实现一个aop的动态注入框架,对emit有了更加深入的了解,最重要的是,对clr il代码的执行过程有了一定的认知,受益匪浅。

该方法在使用的过程中也发现了问题,比如有ref和out类型的参数时,会出现问题,需要后续继续改进

本文的源代码已托管在github上,又需要可以自行拿取(顺手star哦~):https://github.com/seventiny/codearts (本地下载

该代码的位置在 codearts.csharp 分区下

AOP从静态代理到动态代理(Emit实现)详解

vs打开后,可以在 emitdynamicproxy 分区下找到;本博客所有的测试项目都在项目中可以找到。

AOP从静态代理到动态代理(Emit实现)详解

再次放上源代码地址,供一起学习的朋友参考,希望能帮助到你:https://github.com/seventiny/codearts

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:https://www.cnblogs.com/7tiny/p/9657451.html

延伸 · 阅读

精彩推荐
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20