AOP面向切面编程(Aspect Oriented Programming),是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。Spring框架用的核心技术就是AOP,是函数式编程的一种衍生范型。利用AOP的好处就是可以对业务逻辑进行隔离,降低耦合度,提高程序的可重用性,同时提高了开发的效率。开源的AOP也有不少,我这里用的KingAOP.
1 项目结构
2 定义一个日志记录的实体类User和LoggingAspect切面日志类
1 namespace AOPDemo.Logging 2 { 3 class User 4 { 5 public int ID { get; set; } 6 public string Name { get; set; } 7 public string Pwd{get;set;} 8 public string IP { get; set; } 9 public string State { get; set; } 10 public System.DateTime LoginTime { get; set; } 11 12 } 13 }
1 using System; 2 using System.Text; 3 using KingAOP.Aspects; 4 5 namespace AOPDemo.Logging 6 { 7 internal class LoggingAspect : OnMethodBoundaryAspect 8 { 9 public override void OnEntry(MethodExecutionArgs args) 10 { 11 string logData = CreateLogData("Entering", args); 12 Console.WriteLine(logData); 13 } 14 15 public override void OnExit(MethodExecutionArgs args) 16 { 17 string logData = CreateLogData("Leaving", args); 18 Console.WriteLine(logData); 19 } 20 /// <summary> 21 /// AOP对于登录日志逻辑,只需在此进行修改即可,无需修改被切面的处理类 22 /// </summary> 23 /// <param name="methodStage"></param> 24 /// <param name="args"></param> 25 /// <returns></returns> 26 private string CreateLogData(string methodStage, MethodExecutionArgs args) 27 { 28 var str = new StringBuilder(); 29 str.AppendLine(); 30 str.AppendLine(string.Format(methodStage + " {0} ", args.Method)); 31 foreach (var argument in args.Arguments) 32 { 33 var argType = argument.GetType(); 34 35 str.Append(argType.Name + ": "); 36 37 if (argType == typeof(string) || argType.IsPrimitive) 38 { 39 str.Append(argument); 40 } 41 else 42 { 43 foreach (var property in argType.GetProperties()) 44 { 45 str.AppendFormat("{0} = {1}; ", 46 property.Name, property.GetValue(argument, null)); 47 } 48 } 49 } 50 return str.ToString(); 51 } 52 } 53 }
3 Login类
该类必须实现IDynamicMetaObjectProvider的GetMetaObject方法,同时在需要切面的方法上用属性[LoggingAspect]进行标注,LoggingAspect属性也就是我们上面定义的LoggingAspect切片处理类.
1 using System.Dynamic; 2 using System.Linq.Expressions; 3 using KingAOP; 4 namespace AOPDemo.Logging 5 { 6 /// <summary> 7 /// 登录逻辑处理,只需添加一个LoggingAspect即可实现日志功能,达到逻辑和通用处理的逻辑分离 8 /// </summary> 9 internal class Login : IDynamicMetaObjectProvider 10 { 11 //添加登录切面 12 [LoggingAspect] 13 public void LoginValdate(User entity) 14 { 15 //只需进行业务逻辑处理,无需进行日志处理 16 if (entity.Name == "jack" && entity.Pwd == "wang") 17 { 18 entity.State = "Logged"; 19 } 20 else 21 { 22 entity.State = "Error"; 23 } 24 25 26 } 27 /// <summary> 28 /// IDynamicMetaObjectProvider的实现 29 /// </summary> 30 /// <param name="parameter"></param> 31 /// <returns></returns> 32 public DynamicMetaObject GetMetaObject(Expression parameter) 33 { 34 //need for AOP weaving 35 return new AspectWeaver(parameter, this); 36 } 37 } 38 }
调试代码如下:
1 //测试感觉KingAOP必须有一个dynamic才能切面 2 Logging.Login test = new Logging.Login(); 3 dynamic entity = new Logging.User { Name = "Jon", ID = 99,Pwd="wang",State="",LoginTime=System.DateTime.Now}; 4 test.LoginValdate(entity);
时间: 2024-10-05 16:53:48