ASP.NET Core 3 使用原生 依赖注入 集成 AspectCore ,实现 AOP 功能
在NETCORE中可以使用AOP的方式有很多很多,包括国内优秀的开源框架asp.netcore同样可以实现AOP编程模式。
IOC方面,个人喜欢net core 3自带的DI,因为他注册服务简洁优雅,3个生命周期通俗易懂,所以就没使用autofac等其他容器,AOP方面,使用了AspectCore 所以要在nuget中添加AspectCore.Extensions.DependencyInjection的依赖包,这里大家可能会有疑问,利用mvc的actionFilter不就可以实现了么,为什么还要引用DP呢,因为呀,actionFilter只在controller层有效,普通类他就无能为力了,而DP无所不能。
步骤1、安装 AspectCore.Extensions.DependencyInjection 1.3.0 Nuget包
步骤2、修改 Program.cs
using AspectCore.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace WebApplication4 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) // for aspcectcore .UseServiceProviderFactory(new AspectCoreServiceProviderFactory()); } }
备注:加入 此处解决 下面这个问题
System.NotSupportedException:“ConfigureServices returning an System.IServiceProvider isn't supported
步骤3、添加 CustomInterceptorAttribute.cs 类文件
using AspectCore.DynamicProxy; using System; using System.Threading.Tasks; namespace WebApplication4.Aop { public class CustomInterceptorAttribute : 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"); } } } }
步骤4、实现特性拦截的方式:
using System.Collections.Generic; using WebApplication4.Aop; namespace WebApplication4.App { public class StudentRepository : IStudentRepository { [CustomInterceptor] public List<Student> GetAllStudents() { var students = new List<Student>(); students.Add(new Student { Name = "Panxixi", Age = 11 }); students.Add(new Student { Name = "Liuchuhui", Age = 12 }); return students; } } }
最后、 提供 AspectCore 的 4个demo:
-
InterceptorAttribute demo (特性拦截)
-
GlobalInterceptor demo (全局拦截)
-
NonAspect demo (忽略拦截)
-
DependencyInjection demo
连接地址:https://github.com/fs7744/AspectCoreDemo
![](https://pic4.zhimg.com/v2-749d5c2429ccc1fbefc2d5826f92359b_b.jpg)