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

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);
      }
    
    }

 

五、测试结果

posted @ 2016-02-24 10:47  lee小菜  阅读(381)  评论(0编辑  收藏  举报