【转】IL编织 借助PostSharp程序集实现AOP

本文介绍如何使用PostSharp库结合AOP(面向切面编程)技术在C#中实现方法级别的日志记录功能。通过自定义Attribute,可以在不修改业务逻辑的情况下,为多个方法统一添加日志记录,有效减少代码冗余。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ref:   C# AOP实现方法拦截器 

 

在写程序的时候,很多方法都加了。日志信息。比如打印方法开始,方法结束,错误信息,等等。

由于辅助性功能的代码几乎是完全相同的,这样就会令同样的代码在各个函数中出现,引入了大量冗余代码。

最后找到了AOP解决方案,分享出来。供大家参考。

实现步骤

一、下载安装

PostSharp-1.5.6.629-Release-x86.msi 或者 PostSharp-1.5.7.1081-Release-x64.msi 具体根据自己电脑来。

安装的时候记得先退出自己的 Microsoft Visual Studio
下载地址: http://www.postsharp.net/downloads/postsharp-1.5/sp-1


二、在项目中添加引用


三、实例

  [Serializable] //必须加入这个
  [AttributeUsage(AttributeTargets.Method,AllowMultiple=true,Inherited=true)] //设置类的访问访问
  public sealed class LoggingAttribute:OnMethodBoundaryAspect
  {

    public string BusinessName { get; set; }


    /// <summary>
    /// 方法进入时执行
    /// </summary>
    /// <param name="eventArgs"></param>
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {

      Console.WriteLine("---------------方法:" + eventArgs.Method.Name+"开始--------------");
    }

    /// <summary>
    /// 方法退出时执行
    /// </summary>
    /// <param name="eventArgs"></param>
    public override void OnExit(MethodExecutionEventArgs eventArgs)
    {
      Console.WriteLine("---------------方法:" + eventArgs.Method.Name + "结束--------------");
    }


    /// <summary>
    /// 错误的时候执行
    /// </summary>
    /// <param name="eventArgs"></param>
    public override void OnException(MethodExecutionEventArgs eventArgs)
    {
      base.OnException(eventArgs);
    }

    //还有别的方法自己研究

  }

注意点:类必须序列化 需要加 [Serializable]    类要配置 Attribute  设置的他的调用方式

四 调用 

在需要调用的 方法前面加入方法的 Attribute 就行了

    /// <summary>
    /// 调用事例1
    /// </summary>
    [Logging()]
    void debugInfo() {

      for (int i = 0; i < 3;i++ )
      {
         
        Console.WriteLine("i="+i);
      }
    }


    /// <summary>
    /// 调用事例2 ,可以给属性赋值
    /// </summary>
    [Logging(BusinessName="aaa")]
    void debugError() {
      for (int i = 0; i < 3; i++)
      {

        Console.WriteLine("i=" + i);
      }
    
    }

 

五、测试结果

转载于:https://www.cnblogs.com/leenice/p/5212134.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值