在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
