码迷,mamicode.com
首页 > 其他好文 > 详细

切面编程AOP之Castle.Core

时间:2019-04-18 17:15:54      阅读:1808      评论:0      收藏:0      [点我收藏+]

标签:protected   end   stat   region   aop   []   nuget   new   inter   

1.Nuget中搜索Castle.Core并install 

2.创建一个普通的类(注意类中只有标记virtual才能实现拦截 )

 public class TestInterceptor
    {
        public virtual void MethodInterceptor()
        {
            Console.WriteLine("走过滤器");
        }

        public void NoInterceptor()
        {
            Console.WriteLine("没走过滤器");
        }
    }

3. 创建拦截器

public class Interceptor: StandardInterceptor
    {
        protected override void PreProceed(IInvocation invocation)
        {
            Console.WriteLine("调用前的拦截器, 方法名是: {0}", invocation.Method.Name);
        }

        protected override void PerformProceed(IInvocation invocation)
        {
            Console.WriteLine("拦截的方法返回时调用的拦截, 方法名是: {0}", invocation.Method.Name);
        }

        protected override void PostProceed(IInvocation invocation)
        {
            Console.WriteLine("调用后的拦截器, 方法名是: {0}", invocation.Method.Name);
        }
    }

4. 控制台中调用

static void Main(string[] args)
        {
            #region Castle.Core
            ProxyGenerator generator = new ProxyGenerator(); // 实例化代理生成器
            Interceptor interceptor = new Interceptor(); //实例化拦截器

            //使用代理生成器创建Person对象, 而不是使用new关键字实例化
            TestInterceptor test = generator.CreateClassProxy<TestInterceptor>(interceptor);
            Console.WriteLine("当前类型: {0}, 父类型: {1}", test.GetType(), test.GetType().BaseType);
            Console.WriteLine();
            test.MethodInterceptor();
            Console.WriteLine();
            test.NoInterceptor();
            Console.WriteLine();
            Console.ReadLine();
            #endregion
        }

  

切面编程AOP之Castle.Core

标签:protected   end   stat   region   aop   []   nuget   new   inter   

原文地址:https://www.cnblogs.com/zxhome/p/10730477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!