一、前言
在使用某种技术更多我们在技术选型,只要网上一些能满足需求,我们就直接站在巨人肩膀上前行。
秉着 满足需求、最轻量
的原则,我们选择了社区活跃度比较高的 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)执行后的动作");
没有效果图就没有真相