標籤:
AspectSharp項目地址:AspectSharp - .NET AOP Framework
這個項目從05年開始已經沒有維護了,估計現在已經沒落,現在AOP用的比較多的應該是PostSharp,PostSharp使用上應該非常方便,但前段時間已經商業化運作了,仍提供社區版,但功能上有一些限制
AspectSharp現在網上較完整的例子比較少,從sourceforge下載項目原始碼,裡面有一個example項目,可以使用這個項目大致看一下AspectSharp的使用方式
因為下載的example項目運行時會出錯,而AspectSharp使用的還是Castle.DynamicProxy.dll檔案,我將AspectSharp做了點修改
1. 改成.Net Framework 3.5版本,因為新的Castle DynamicProxy使用的是3.5版本了
2. 改成使用Castle.DynamicProxy2.dll。主要是老的DynamicProxy中不少建立代理的方法、代理的使用方法都發生變化了,老的AspectSharp代碼無法工作
修改之後,這篇文章中的例子以及AspectSharp中的Example項目都能正常運行,從這裡下載附件可以運行這篇文章中的樣本程式。但是因為新的DynamicProxy中攔截器介面機制的改變,無法確保我對AspectSharp的修改一定是正確的,因此這個下載僅用於示範目的
codeproject上面有篇.NET下開源AOP架構的對比文章:Rating of Open Source AOP Frameworks in .Net。AspectSharp在裡面的評價很低,最好的是PostSharp,其次是Unity跟Spring.NET
引用命名空間:
using AopAlliance.Intercept;using AspectSharp.Builder;?
| 1234567891011121314151617181920 |
//測試用的目標類 public class RequestProcessor { //需要是virtual的方法才能攔截 public virtual void Process() { Console.WriteLine("Hello AspectSharp"); } } //記錄日誌用的攔截器 public class LoggerInterceptor : IMethodInterceptor { public object Invoke(IMethodInvocation invocation) { Console.WriteLine("Before {0} on {1}", invocation.Method.Name, invocation.Method.DeclaringType); object returnVal = invocation.Proceed(); Console.WriteLine("After {0} on {1}", invocation.Method.Name, invocation.Method.DeclaringType); return returnVal; } } |
測試代碼如下:
?
| 12345678910111213141516171819202122232425262728293031323334353637 |
static void Main(string[] args) { StandardCall(); AopCall(); Console.ReadKey(); } //正常的調用,不使用AOP攔截 private static void StandardCall() { RequestProcessor rp = new RequestProcessor(); rp.Process(); Console.WriteLine(); } //使用AOP攔截後的調用 private static void AopCall() { //AOP的攔截配置,這些配置可以放入設定檔中 //import: 匯入命名空間,比如攔截器所在的命名空間 //aspect: 定義一個攔截的aspect, for指令用於指示需要攔截的類所在的命名空間 //pointcut: 定義一個攔截點,使用method指定需要攔截的方法,還可以使用property指定需要攔截的屬性, // 或者使用propertyread、propertywrite等用於攔截屬性的getter、setter操作, // 被攔截的方法需要是virtual類型的,否則無法實現攔截(跟Castle Dynamic Proxy機制相關) //advice: 定義攔截器 string config = @" import AspectSharp.Test aspect processor for [AspectSharp.Test] pointcut method(* Process()) advice(LoggerInterceptor) end end"; AspectLanguageEngineBuilder engineBuilder = new AspectLanguageEngineBuilder(config); AspectEngine engine = engineBuilder.Build(); //使用AspectSharp封裝,AspectSharp將根據配置組建代理程式對象,在代理對象上使用攔截器實現AOP攔截處理 RequestProcessor rp = engine.WrapClass(typeof(RequestProcessor)) as RequestProcessor; rp.Process(); Console.WriteLine(); } |
運行結果如下:
從上面可以看到,感覺AspectSharp AOP唯一有點新意的地方就是使用了antlr來定義AOP的配置語言,其實使用動態代理,或者Post Compilation的方式自己實現一下攔截也是比較容易的事情。AspectSharp中使用AOP的地方也還得採取措施對AspectEngine進行封裝,整體來看這個AOP對代碼不是完全透明的上面只是簡單示範了一下AspectSharp的基本用法,因為使用了Castle.DynamicProxy實現AOP,因此AspectSharp也支援mixins等
AOP - AspectSharp 2.1.1.0