项目作者: relyky

项目描述 :
C#, 最簡易的AOP實作, AOP, Aspect
高级语言: C#
项目地址: git://github.com/relyky/SimplestAspectImplementation.git
创建时间: 2019-12-29T02:21:10Z
项目社区:https://github.com/relyky/SimplestAspectImplementation

开源协议:

下载


The Simplest AOP Implementation

C#, 最簡易的AOP實作, AOP, Aspect

實作說明

.Net Framework 4.x 以上。
應用 Action 類別的特性。
好用的 wave 才是好的AOP。
讓交錯複雜的碼變得更易讀懂才符合AOP的精神。

成果紀錄

程式碼片段

  1. LogAspect(() =>
  2. {
  3. Console.WriteLine("step 1");
  4. Console.WriteLine("step 2");
  5. Console.WriteLine("step 3");
  6. });

輸出

  1. BEGIN
  2. step 1
  3. step 2
  4. step 3
  5. END
#### 程式碼片段 ````Csharp int runTimes = 0; WhileAspect(true, () => LogAspect(() => IgnoreAspect(() => RetryAspect(2, 3000, () => { Console.WriteLine($"times: {++runTimes}"); Console.WriteLine("step 1"); Console.WriteLine("step 2"); if (runTimes < 3) throw new ApplicationException("例外測試"); Console.WriteLine("step 3"); })))); ```` #### 輸出
  1. while true go
  2. BEGIN
  3. times: 1
  4. step 1
  5. step 2
  6. Exception 例外測試 retry
  7. times: 2
  8. step 1
  9. step 2
  10. Exception 例外測試 retry
  11. times: 3
  12. step 1
  13. step 2
  14. step 3
  15. END

程式碼片段

  1. int runTimes = 0;
  2. WhileAspect(true, () =>
  3. LogAspect(() =>
  4. IgnoreAspect(() =>
  5. CatchAspect<ApplicationException>(ex => {
  6. Console.WriteLine("I got you. → {0}", ex.Message);
  7. throw ex; // throw out or not
  8. }, ()=>
  9. RetryAspect(2, 3000, () =>
  10. {
  11. Console.WriteLine($"times: {++runTimes}");
  12. Console.WriteLine("step 1");
  13. Console.WriteLine("step 2");
  14. //if(runTimes < 3) throw new ApplicationException("例外測試");
  15. throw new ApplicationException("例外測試");
  16. Console.WriteLine("step 3");
  17. })))));

輸出

  1. while true go
  2. BEGIN
  3. times: 1
  4. step 1
  5. step 2
  6. Exception 例外測試 retry
  7. times: 2
  8. step 1
  9. step 2
  10. Exception 例外測試 retry
  11. times: 3
  12. step 1
  13. step 2
  14. Catch ApplicationException
  15. I got you. 例外測試
  16. Exception 例外測試 ignore
  17. END

程式碼片段

  1. LogAspect(() =>
  2. IgnoreAspect(() =>
  3. CatchAspect<ApplicationException>(handleCatch, ()=>
  4. {
  5. Console.WriteLine("step 1");
  6. Console.WriteLine("step 2");
  7. throw new ApplicationException("例外測試");
  8. Console.WriteLine("step 3");
  9. })));
  1. /// handler function
  2. void handleCatch(ApplicationException ex) {
  3. Console.WriteLine("I got you. → {0}", ex.Message);
  4. throw ex; // throw out or not
  5. }

輸出

  1. BEGIN
  2. step 1
  3. step 2
  4. Catch ApplicationException
  5. I got you. 例外測試
  6. Exception 例外測試 ignore
  7. END