• 利用Lambda表达式、扩展方法以及泛型来实现一个另类的AOP


    假设我们有如下的代码

        public class SecurityServiceProxy
      {
        public string Encrypt(string input)
        {
          try
          {
            return new SecurityServiceClient().Encrypt(input);
          }
          catch(Exception ex)
          {
            //Log Exception
            throw;
          }
        }

        public string Decrypt(string input)
        {
          try
          {
            return new SecurityServiceClient().Decrypt(input);
          }
          catch(Exception ex)
          {
            //Log Exception
            throw;
          }
        }
      }

    这个代码中有两段重复(异常处理块重复以及在异常时记Log的逻辑重复),这个重复从AOP的角度来看的话应该是属于横切关注点,所以如果能以AOP的方式解决那应该是最好的方案了,以下实现了一种特殊形式的AOP,代码如下:

        public class SecurityServiceProxy
      {
        public string Encrypt(string input)
        {
         return new SecurityServiceClient().ExecAndLogExcetion(client => client .Encrypt(input));
        }

        public string Decrypt(string input)
        {
         return new SecurityServiceClient().ExecAndLogExcetion(client => client .Decrypt(input));
        }
      }

    现在的代码已经简捷多了,这主要是因为利用到了如下的扩展方法:

        public static class ObjectExtensions
    {
    public static void LockExec<T>(this T obj, Action<T> action) where T : class
    {
    lock (obj)
    {
    action(obj);
    }
    }

    public static void ExecAndLogExcetion<T>(this T obj, Action<T> action)
    {
    try
    {
    action(obj);
    }
    catch (Exception)
    {
    //log excetion
    throw;
    }
    }

    public static void ExecAndLogExcetion<T1, T2>(this T1 obj, T2 obj1, Action<T1, T2> action)
    {
    try
    {
    action(obj, obj1);
    }
    catch (Exception)
    {
    //log excetion
    throw;
    }
    }

    public static TResult ExecAndLogExcetion<T, TResult>(this T obj, Func<T, TResult> func)
    {
    try
    {
    return func(obj);
    }
    catch (Exception)
    {
    //log excetion
    throw;
    }
    }

    public static TResult ExecAndLogExcetion<T1, T2, TResult>(this T1 obj, T2 obj1, Func<T1, T2, TResult> func)
    {
    try
    {
    return func(obj, obj1);
    }
    catch (Exception)
    {
    //log excetion
    throw;
    }
    }
    }
  • 相关阅读:
    bootstrap中nav-fixed-top和nav-static-top的区别
    bootstrap aria
    pixi学习总结
    我的代码需要随时备份,并且保证最新版与别人协同开发?Git与Github一起用啊
    自己本地的代码,如何随时备份?随时找回上个备份?版本控制工具Git啊
    自己的代码,如何跟别人协同开发?用GitHub啊
    函数放到onload里面,在html里面执行函数会报错-----作用域和闭包相关问题
    使用CSS实现空心的向上向下的箭头
    两个input放一行不能对齐
    发现一个h5网站,爱果果
  • 原文地址:https://www.cnblogs.com/zanxiaofeng/p/1930171.html
Copyright © 2020-2023  润新知