关于在C#中实现AOP 拦截编程模式的新的探索

前面有篇文章,是从其他个人博客中贴过来的。地址:http://www.lanhusoft.com/Article/240.html

作者总结实现的挺好。

但是。不能不考虑性能!!使用

ContextBoundObject和Attribute实现AOP技术

实现的,比Native的方式调用 ,至少慢300度倍!!!!这个实在不敢恭维。

实现AOP的框架也很多,但是都比较麻烦,调用也比较麻烦。比如 使用 Spring.Net(已经N年没更新了)的拦截。。。

 http://www.springframework.net/doc-latest/reference/html/aop.html

 http://www.cnblogs.com/GoodHelper/archive/2009/11/21/SpringNet_blogs.html

以前在设计实现的时候都是使用 Unity容器 进行IOC 后,对实例进行拦截注册。Unity 包含了拦截功能,支持属性拦截。具体实现,参考官方文档或者百度。

但是,如果不想使用基于IOC容器也不想使用代理的方式。那就比较的有难度了。

基于Mono项目的 Mono.Ceil支持IL代码注入。从此  基于  IL级别的AOP注入拦截成了比较好的方式,省心省事还性能高。

典型的比如 PostSharp项目。但是这个项目  开始商业运营 ,收费的咱就撸过了。

综合比较了下各种实现AOP的技术。在.Net 架构下,仿照PostSharp项目的功能,实现项目解耦的Fody项目,确实比较优秀。

Fody项目:开源

http://www.nuget.org/packages/Fody/

http://github.com/Fody/Fody

而且支持插件化.

也不知道 “weaving” 这个 编织技术算是什么概念。个人理解是将程序项目进行穿插解析,分析目标成员,进行指定操作的修改。

Fody项目是基于 Mono.Ceil项目,解析 .net 程序集,对程序集进行静态分析。

Extensible tool for weaving .net assemblies

Why?

This technique of "weaving" in new instructions is fantastically powerful.

You can turn simple public properties into fullINotifyPropertyChanged implementations,

add checks for null arguments,

add Git hashes to your Assemblies,

even make all your string comparisons case insensitive.

The plumbing tasks Fody handles

  • Injection of the MSBuild task into the build pipeline
  • Resolving the location of the assembly and pdb
  • Abstracts the complexities of logging to MSBuild
  • Reads the assembly and pdb into the Mono.Cecil object model
  • Re-applying the strong name if necessary
  • Saving the assembly and pdb

Fody Uses Mono.Cecil and an add-in based approach to modifying the IL of .net assemblies at compile time.

  • No install required to build
  • No attributes required
  • No references required
  • Supports .net 3.5, .net 4, .net 4.5, .net 4.6, Silverlight 4, Silverlight 5, Windows Phone 7, Windows Phone 8, Metro on Windows 8, Mono, MonoTouch, MonoDroid and PCL

然后使用插件之一:https://github.com/ArxOne/MrAdvice  实现拦截。

具体实现看官方的例子即可。十分的简单实用,而且效率虽然比不上PostSharp。但是效率也绰绰有余了。。。Good luck.

原文地址:https://www.cnblogs.com/micro-chen/p/5788100.html