码迷,mamicode.com
首页 > Web开发 > 详细

.net AOP Castle.Core

时间:2018-11-15 18:33:07      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:调用   ati   inter   方法   ica   standard   voc   div   RoCE   

参考资料:http://www.cnblogs.com/zuowj/p/7501896.html

1、通过NuGet下载Castle.Core

2、创建代理类并继承StandardInterceptor

技术分享图片

参考代码如下

技术分享图片
using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class TestInterceptor : StandardInterceptor
    {
        /// <summary>
        /// 创建代理类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T CreateProxy<T>() where T : class
        {
            ProxyGenerator generator = new ProxyGenerator();
            var testa = generator.CreateClassProxy<T>(new TestInterceptor());
            return testa;
        }
        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PreProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行前,入参:" + string.Join(",", invocation.Arguments));
        }

        /// <summary>
        /// 执行中
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PerformProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行中");
            try
            {
                base.PerformProceed(invocation);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        /// <summary>
        /// 执行后
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PostProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行后,返回值:" + invocation.ReturnValue);
        }
    }
}
View Code

3、创建测试类

public class TestB
    {
        public virtual string GetResult()
        {
            string str = DateTime.Now + "TestB-GetResult";
            Console.WriteLine(str);
            return str;
        }

        public virtual string GetResult2()
        {
            string str = DateTime.Now + "TestB-GetResult2";
            Console.WriteLine(str);
            return str;
        }
    }

4、使用AOP方式调用方法

TestInterceptor.CreateProxy<TestB>().GetResult();

重点:virtual 

Castle只会对virtual标记的虚方法进行代理

.net AOP Castle.Core

标签:调用   ati   inter   方法   ica   standard   voc   div   RoCE   

原文地址:https://www.cnblogs.com/jianghaidong/p/9964781.html

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