C#面向切面編程之AspectCore用法詳解
寫在前面
AspectCore 是Lemon名下的一個國產(chǎn)Aop框架,提供了一個全新的輕量級和模塊化的Aop解決方案。面向切面也可以叫做代碼攔截,分為靜態(tài)和動態(tài)兩種模式,AspectCore 可以實現(xiàn)動態(tài)代理,支持程序運行時在內(nèi)存中“臨時”生成 AOP 動態(tài)代理類。
老規(guī)矩從 Nuget 安裝 AspectCore.Extensions.DependencyInjection 包。

代碼實現(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)用示例

如圖,代理類將Say方法包裹了起來。
如果修改一下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");
}
}
}
運行代碼 Person中的Say方法本體就被跳過了:

到此這篇關(guān)于C#面向切面編程之AspectCore用法詳解的文章就介紹到這了,更多相關(guān)C# AspectCore內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實現(xiàn)關(guān)閉子窗口而不釋放子窗口對象的方法
下面小編就為大家?guī)硪黄狢#實現(xiàn)關(guān)閉子窗口而不釋放子窗口對象的方法 。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
c# socket網(wǎng)絡(luò)編程接收發(fā)送數(shù)據(jù)示例代碼
這篇文章主要介紹了c# socket網(wǎng)絡(luò)編程,server端接收,client端發(fā)送數(shù)據(jù),大家參考使用吧2013-12-12
c#中Empty()和DefalutIfEmpty()用法分析
這篇文章主要介紹了c#中Empty()和DefalutIfEmpty()用法,以實例形式分析了針對不同情況下Empty()和DefalutIfEmpty()用法區(qū)別,需要的朋友可以參考下2014-11-11

