用Castle.Core实现方法拦截器

1.去NuGet下载 Castle.Core.dll

2.建一个普通的类。注意:本类2个方法,测试是否走拦截器。这里只有标记Virtual才能实现方法拦截。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

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

 

3.拦截器 重写拦截器方法:

PreProcced,在进入拦截的方法之前调用。PerformProceed,在拦截的方法返回时调用。PostProcced,在拦截的方法运行完成后调用。 代码如下:

using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Castle
{
   public class Interceptor: StandardInterceptor
    {
        /// <summary>
        /// 调用前的拦截器
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PreProceed(IInvocation invocation)
        {
            Console.WriteLine("调用前的拦截器,方法名是:{0}。", invocation.Method.Name);// 方法名   获取当前成员的名称。 
        }
        /// <summary>
        /// 拦截的方法返回时调用的拦截器
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PerformProceed(IInvocation invocation)
        {
            Console.WriteLine("拦截的方法返回时调用的拦截器,方法名是:{0}。", invocation.Method.Name);
            base.PerformProceed(invocation); 
        }

        /// <summary>
        /// 调用后的拦截器
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PostProceed(IInvocation invocation)
        {
            Console.WriteLine("调用后的拦截器,方法名是:{0}。", invocation.Method.Name); 
        }
    }
}
View Code

 

4.调用

using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Castle
{
    class Program
    {
        static void Main(string[] args)
        {
            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();
        }
    }
}
View Code

 

5.输出结果:

 

posted @ 2017-08-31 19:10  01234  阅读(4498)  评论(0编辑  收藏  举报