首页 > 编程 > C# > 正文

C#开源的AOP框架--KingAOP基础

2020-01-24 01:20:30
字体:
来源:转载
供稿:网友

  AOP面向切面编程(Aspect Oriented Programming),是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。Spring框架用的核心技术就是AOP,是函数式编程的一种衍生范型。利用AOP的好处就是可以对业务逻辑进行隔离,降低耦合度,提高程序的可重用性,同时提高了开发的效率。开源的AOP也有不少,我这里用的KingAOP.

1 项目结构

2 定义一个日志记录的实体类User和LoggingAspect切面日志类

namespace AOPDemo.Logging{ class User {  public int ID { get; set; }  public string Name { get; set; }  public string Pwd{get;set;}  public string IP { get; set; }  public string State { get; set; }  public System.DateTime LoginTime { get; set; } }}

 

using System;using System.Text;using KingAOP.Aspects;namespace AOPDemo.Logging{ internal class LoggingAspect : OnMethodBoundaryAspect {  public override void OnEntry(MethodExecutionArgs args)  {   string logData = CreateLogData("Entering", args);   Console.WriteLine(logData);  }  public override void OnExit(MethodExecutionArgs args)  {   string logData = CreateLogData("Leaving", args);   Console.WriteLine(logData);  }  /// <summary>  /// AOP对于登录日志逻辑,只需在此进行修改即可,无需修改被切面的处理类  /// </summary>  /// <param name="methodStage"></param>  /// <param name="args"></param>  /// <returns></returns>  private string CreateLogData(string methodStage, MethodExecutionArgs args)  {   var str = new StringBuilder();   str.AppendLine();   str.AppendLine(string.Format(methodStage + " {0} ", args.Method));   foreach (var argument in args.Arguments)   {    var argType = argument.GetType();    str.Append(argType.Name + ": ");    if (argType == typeof(string) || argType.IsPrimitive)    {     str.Append(argument);    }    else    {     foreach (var property in argType.GetProperties())     {      str.AppendFormat("{0} = {1}; ",       property.Name, property.GetValue(argument, null));     }    }   }   return str.ToString();  } }}

3 Login类

该类必须实现IDynamicMetaObjectProvider的GetMetaObject方法,同时在需要切面的方法上用属性[LoggingAspect]进行标注,LoggingAspect属性也就是我们上面定义的LoggingAspect切片处理类.

using System.Dynamic;using System.Linq.Expressions;using KingAOP;namespace AOPDemo.Logging{ /// <summary> /// 登录逻辑处理,只需添加一个LoggingAspect即可实现日志功能,达到逻辑和通用处理的逻辑分离 /// </summary> internal class Login : IDynamicMetaObjectProvider {  //添加登录切面  [LoggingAspect]   public void LoginValdate(User entity)  {   //只需进行业务逻辑处理,无需进行日志处理   if (entity.Name == "jack" && entity.Pwd == "wang")   {    entity.State = "Logged";   }   else   {    entity.State = "Error";   }     }  /// <summary>  /// IDynamicMetaObjectProvider的实现  /// </summary>  /// <param name="parameter"></param>  /// <returns></returns>  public DynamicMetaObject GetMetaObject(Expression parameter)  {   //need for AOP weaving   return new AspectWeaver(parameter, this);  } }}

调试代码如下:

//测试感觉KingAOP必须有一个dynamic才能切面Logging.Login test = new Logging.Login();dynamic entity = new Logging.User { Name = "Jon", ID = 99,Pwd="wang",State="",LoginTime=System.DateTime.Now};test.LoginValdate(entity);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表