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(interceptor); Console.WriteLine("当前类型: {0}, 父类型: {1}", test.GetType(), test.GetType().BaseType); Console.WriteLine(); test.MethodInterceptor(); Console.WriteLine(); test.NoInterceptor(); Console.WriteLine(); Console.ReadLine(); #endregion }