標籤:
SheepAspect 簡介以及代碼示列:
SheepAspect是一個AOP架構為.NET平台,深受AspectJ。它靜織目標組件作為一個編譯後的任務(編譯時間把AOP代碼植入)。
多有特性時,可根據參數值設定先後進入順序
下面開始代碼實現之旅:
一、建立控制台程式:方案名稱:SheepAectTest
二、NuGet上搜尋SheepAspect進行安裝
三、安裝完畢後的樣子
成員的切入點類型(SelectMethdos 以等):
"saql":
| Criteria |
Argument |
Examples |
| Name |
string |
- Name: ‘*Customer’
- Name: (‘*Service’ | ‘*Repository’)
|
| Namespace |
string |
|
| ImplementsType |
Type Pointcut |
- ImplementsType:’System.Collections.IEnumerable’
- ImplementsType: (Name: ‘*Repository’ | Namespace: ‘*.DataContexts’)
|
| AssignableToType |
Type Pointcut |
- AssignableToType:(‘System.Collections.*’ & Interface)
- AssignableToType: Namespace: ‘System.Collections.*’
|
| HasMethod |
Method Pointcut |
- HasMethod: Name: ‘Get*’
- HasMethod: (Public & Args(‘System.Int32’)
|
| HasProperty |
Property Pointcut |
- HasProperty:Name:’Length’
- HasProperty:Type:Implements:’*.*Service’
|
| HasField |
Field Pointcut |
- HasField:Name:(‘_createdDate’ | ‘_entryDate’)
- HasField:((Public & Static) | Protected)
|
| ThisAspect |
(none) |
- ThisAspect
- Implements:ThisAspect
- Namespace:’Sheep.*’ & !ThisAspect
|
| HasCustomAttributeType |
Type Pointcut |
- HasCustomAttributeType:ImplementsType:’BindableAttribute’
|
| InheritsType* |
Type Pointcut |
- InheritsType:Namespace:’System.Collections’
|
| Interface* |
(none) |
|
| Abstract* |
(none) |
- Abstract & Name:’*Strategy’
|
| ValueType* |
(none) |
- ValueType & HasMethod:Name:’Equals’
|
| Class* |
(none) |
- Class & Implements:’Sheep.Irepository’
|
特性植入示列:
一、建立特性
public class LogAttribute:Attribute { public string Name { get; set; } public LogAttribute(string name) { Name = name; } }
二、建立一個測試類別TestClass.cs
public class TestClass { [Log("擷取的第一個方法")] public string Get() { return "test1"; } public string Get2() { return "test2"; } }
三、更改SampleAspect為:HasCustomAttributeType:‘SheepAectTest.Attr.LogAttribute‘ > 命名空間+類名
四:編寫測試代碼:
輸出結果:
如果我們在AOP中更改結果呢?
輸出結果:
擷取特性的屬性:
[Aspect] public class SampleAspect { [SelectMethods("HasCustomAttributeType:‘SheepAectTest.Attr.LogAttribute‘")] public void PublicMethods() { } [Around("PublicMethods", Priority = 100)] public object LogAroundMethod(MethodJointPoint jp) { try { var log = (LogAttribute)jp.Method.GetCustomAttributes(typeof(LogAttribute), false)[0]; //這樣可以擷取屬性名稱:log.Name; //jp.Args -> 包含傳遞參數 var result = jp.Execute(); if (jp.Method.ReturnType == typeof(void)) result = "{void}"; result = "AOP更改結果"; return result; } catch (Exception e) { throw; } } }
多個特性注入順序以:Priority屬性值控制優先順序較低的值;
瘋狂的果子來源:http://incsharp.cnblogs.com/ 聲明:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格地址,如發現錯誤,歡迎批評指正。如有特殊需求請與本人聯絡!
433685124QQ群
.NET中AOP方便之神SheepAspect