定义函数A,B,C,调用A->B->C,这样就形成了函数静态调用链,而AOP要做的是能动态的添加多个B,形成A->B1->B2->B3...->C这样的效果,在EntLib(MS的企业库)Unity中有这样的实现,不过要看明白里面的代码的确需要花不少脑子,3年前看过里面的代码并做了记录,但是这两天翻出来看时照样化了很大精力,并杀死杀伤大量脑细胞,于是痛下决心将整个过程整理并画出时序图。

测试代码:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BLLObj bll = new BLLObj();
            InterceptionUtil util = new InterceptionUtil();
            util.Pipeline.InterceptionBehaviors.Add(new BehaviorA() { Id = "1" });
            util.Pipeline.InterceptionBehaviors.Add(new BehaviorA() { Id = "2" });
            util.Pipeline.InterceptionBehaviors.Add(new BehaviorA() { Id = "3" });

            var r = util.Call(bll, "Add", new object[] { 3, 4 });
            Console.WriteLine("结果:" + r);

            Console.WriteLine(new string('-', 40));

            var r1 = util.Call(bll, "Concat", new object[]{ new object[] { "a",1, "b", 2 }});
            Console.WriteLine("结果:" + r1);


            Console.WriteLine(new string('-', 40));

            var r2 = util.Call(bll, "DoSome", new object[] { });
            Console.WriteLine("结果:" + r2);
        }
    }

    #region 测试业务类

    public class BLLObj
    {
        public int Add(int a, int b)
        {
            Console.WriteLine("Add");
            return a + b;
        }
        public string Concat(object[] args)
        {
            Console.WriteLine("Concat");
            return string.Concat(args);
        }
        public void DoSome()
        {
            Console.WriteLine("DoSome");
        }

    }
    #endregion
View Code

相关文章: