IBatis.Net学习笔记十一:Castle.DynamicProxy的使用

castle是另外一个框架,包含了aop、ioc、orm等多个方面,其中的castle.dynamicproxy可以实现 动态代理的功能,这个也是很多框架的基础。在ibatis.net中就是使用了castle.dynamicproxy来实现数据库连接等动态操作的。同 时在nhibernet等其他框架中也使用到了这个技术。
下面我通过一个简单例子来看一下如何在我们的代码中调用castle.dynamicproxy:
一般情况下要有三个类:
1、接口类:
using system;
using system.collections.generic;
using system.text;

namespace gspring.castletest
{
    public interface itest
    {
        string getname(string pre);
    }
}
2、实现类:
using system;
using system.collections.generic;
using system.text;

namespace gspring.castletest
{
    public class test : itest
    {
        public string getname(string pre)
        {
            return pre + ",gspring";
        }
    }
}
这两个都很普通的接口和实现
3、代理类:
using system;
using system.collections;
using system.reflection;
using castle.dynamicproxy;

namespace gspring.castletest
{
    /**//// <summary>
    /// summary description for daoproxy.
    /// </summary>
    public class interceptorproxy : iinterceptor
    {
         public object intercept(iinvocation invocation, params object[] arguments)
        {
            object result = null;

            //这里可以进行数据库连接、打日志、异常处理、权限判断等共通操作
            result = invocation.proceed(arguments);

            return result;
        }

    }
}
这个类首先实现接口iinterceptor,然后就可以在方法intercept中加入我们自己的逻辑

然后看一下调用的方式:
        proxygenerator proxygenerator = new proxygenerator();
        iinterceptor handler = new interceptorproxy();
        type[] interfaces = { typeof(itest) };
        test test = new test();
        itest itest = (proxygenerator.createproxy(interfaces, handler, test) as itest);
        string result = itest.getname("hello");最后一句调用的地方,实际会首先执行interceptorproxy类中的intercept方法。

转载于:https://www.cnblogs.com/zyfking/archive/2009/01/19/1378525.html

猜你喜欢

转载自blog.csdn.net/weixin_34205076/article/details/93251770