一、前言
在使用某種技術更多我們在技術選型,只要網上一些能滿足需求,我們就直接站在巨人肩膀上前行。
秉着 滿足需求、最輕量
的原則,我們選擇了社區活躍度比較高的 Asp.Net Core
平臺的 AOP
開源框架組件 AspectCore
。
GitHub地址:https://github.com/dotnetcore/AspectCore-Framework
二、使用方法
使用 AspectCore
需要幾個步驟:
- 引入最新版Nuget包:
AspectCore.Core
、AspectCore.Extensions.Hosting
。- 繼承
AbstractInterceptorAttribute
並實現抽象添加我們自定義AOP
動作。- 在
Program.cs
、Startup.cs
啓用與添加代理配置。- 添加過濾。
ps:網上博客大多引入 AspectCore.Core
、AspectCore.Extensions.DependencyInjection
,其實是一樣的只是 AspectCore
在 AspectCore.Extensions.DependencyInjection
這個基礎之上爲了使用者方便再封裝了一層單獨成立了一個擴展項目 AspectCore.Extensions.Hosting
直接擼框架源碼便知道了啦,嫌麻煩也沒問題,待會我直接貼框架代碼。
三、具體實現
(一)引入最新版Nuget包
(二) 繼承 AbstractInterceptorAttribute
並實現抽象添加我們自定義 AOP
動作
using System;
using System.Threading.Tasks;
using AspectCore.DynamicProxy;
namespace SB.Sample.WebApi.Services
{
public class CustomFilterAttribute : AbstractInterceptorAttribute
{
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
try
{
Console.WriteLine("AOP(before)執行前的動作");
await next(context);
}
catch (Exception ex)
{
Console.WriteLine($"Error:{ex}");
}
finally
{
Console.WriteLine("AOP(after)執行後的動作");
}
}
}
}
(三)啓用與代理配置
1.啓用代理
AspectCore
框架相關代碼,有好幾種用法,有興趣自己git克隆代碼研究
2.添加代理配置
public void ConfigureServices(IServiceCollection services)
{
// AspectCore 根據屬性注入配置全局 AOP 過濾器
services.ConfigureDynamicProxy(config =>
{
config.Interceptors.AddTyped<CustomFilterAttribute>();//CustomInterceptorAttribute這個是需要全局攔截的攔截器
});
//...
services.AddMvc();
services.AddScoped<IAOPTestService, AOPTestService>();
//...
}
(四)添加過濾
再配上一個api調用service服務
預想的結果應該是執行這樣的順序並輸出
Console.WriteLine("DefaultController 執行動作...");
Console.WriteLine("AOP(before)執行前的動作");
Console.WriteLine("AOPTestService 執行動作...");
Console.WriteLine("AOP(after)執行後的動作");
沒有效果圖就沒有真相