前面有篇文章,是從其他個人博客中貼過來的。地址: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.