用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.输出结果:

 

转载于:https://www.cnblogs.com/liudehua0/p/7460030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值