Castle.DynamicProxy在iBATIS.NET中的使用
Castle是另外一個框架,包含了AOP、IOC、ORM等多個方面,其中的Castle.DynamicProxy可以實現(xiàn)動態(tài)代理的功能,這個也是很多框架的基礎(chǔ)。在IBatis.Net中就是使用了Castle.DynamicProxy來實現(xiàn)數(shù)據(jù)庫連接等動態(tài)操作的。同時在NHibernet等其他框架中也使用到了這個技術(shù)。
下面我通過一個簡單例子來看一下如何在我們的代碼中調(diào)用Castle.DynamicProxy:
一般情況下要有三個類:
1、接口類:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace GSpring.CastleTest
- {
- public interface ITest
- {
- string GetName(string pre);
- }
- }
2、實現(xiàn)類:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace GSpring.CastleTest
- {
- public class Test : ITest
- {
- public string GetName(string pre)
- {
- return pre + ",GSpring";
- }
- }
- }
這兩個都很普通的接口和實現(xiàn)
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;
- //這里可以進行數(shù)據(jù)庫連接、打日志、異常處理、權(quán)限判斷等共通操作
- result = invocation.Proceed(arguments);
- return result;
- }
- }
- }
這個類首先實現(xiàn)接口IInterceptor,然后就可以在方法Intercept中加入我們自己的邏輯
然后看一下調(diào)用的方式:
- 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");
最后一句調(diào)用的地方,實際會首先執(zhí)行InterceptorProxy類中的Intercept方法。
以上就是在iBATIS.NET中通過Castle.DynamicProxy實現(xiàn)動態(tài)代理的功能,希望對你有所幫助。
【編輯推薦】