C#面向切面編程之AspectCore用法詳解
寫(xiě)在前面
AspectCore 是Lemon名下的一個(gè)國(guó)產(chǎn)Aop框架,提供了一個(gè)全新的輕量級(jí)和模塊化的Aop解決方案。面向切面也可以叫做代碼攔截,分為靜態(tài)和動(dòng)態(tài)兩種模式,AspectCore 可以實(shí)現(xiàn)動(dòng)態(tài)代理,支持程序運(yùn)行時(shí)在內(nèi)存中“臨時(shí)”生成 AOP 動(dòng)態(tài)代理類(lèi)。
老規(guī)矩從 Nuget 安裝 AspectCore.Extensions.DependencyInjection 包。
代碼實(shí)現(xiàn)
using AspectCore.DynamicProxy; public class Program { public static void Main(string[] args) { Console.WriteLine("Start..."); ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder(); using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build()) { Person p = proxyGenerator.CreateClassProxy<Person>(); Console.WriteLine(p.GetType().BaseType); p.Say($"{Environment.NewLine} Hello World!"); } Console.WriteLine("End"); Console.ReadLine(); } } public class CustomInterceptor : AbstractInterceptorAttribute { public async override Task Invoke(AspectContext context, AspectDelegate next) { try { Console.WriteLine("Before service call"); await next(context); } catch (Exception) { Console.WriteLine("Service threw an exception!"); throw; } finally { Console.WriteLine("After service call"); } } } public class Person { [CustomInterceptor] public virtual void Say(string msg) { Console.WriteLine("service calling..." + msg); } }
調(diào)用示例
如圖,代理類(lèi)將Say方法包裹了起來(lái)。
如果修改一下CustomInterceptor 的Invoke方法,可以直接根據(jù)條件控制代碼的分支跳轉(zhuǎn)。
public class CustomInterceptor : AbstractInterceptorAttribute { public async override Task Invoke(AspectContext context, AspectDelegate next) { try { Console.WriteLine("Before service call"); if (false) await next(context); else await Task.Delay(1000); } catch (Exception) { Console.WriteLine("Service threw an exception!"); throw; } finally { Console.WriteLine("After service call"); } } }
運(yùn)行代碼 Person中的Say方法本體就被跳過(guò)了:
到此這篇關(guān)于C#面向切面編程之AspectCore用法詳解的文章就介紹到這了,更多相關(guān)C# AspectCore內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)關(guān)閉子窗口而不釋放子窗口對(duì)象的方法
下面小編就為大家?guī)?lái)一篇C#實(shí)現(xiàn)關(guān)閉子窗口而不釋放子窗口對(duì)象的方法 。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01Unity OnGUI實(shí)時(shí)顯示游戲FPS
這篇文章主要為大家詳細(xì)介紹了Unity OnGUI實(shí)時(shí)顯示游戲FPS,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11c# socket網(wǎng)絡(luò)編程接收發(fā)送數(shù)據(jù)示例代碼
這篇文章主要介紹了c# socket網(wǎng)絡(luò)編程,server端接收,client端發(fā)送數(shù)據(jù),大家參考使用吧2013-12-12C#獲取系統(tǒng)當(dāng)前日期和時(shí)間的示例詳解
這篇文章主要為大家詳細(xì)介紹了C#如何使用DateTime的Now靜態(tài)屬性動(dòng)態(tài)獲得系統(tǒng)當(dāng)前日期和時(shí)間,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下2024-01-01c#中Empty()和DefalutIfEmpty()用法分析
這篇文章主要介紹了c#中Empty()和DefalutIfEmpty()用法,以實(shí)例形式分析了針對(duì)不同情況下Empty()和DefalutIfEmpty()用法區(qū)別,需要的朋友可以參考下2014-11-11