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、實作類:
public class Test : ITest
public string GetName(string pre)
{
return pre + ",GSpring";
}
這兩個都很普通的接口和實作
3、代理類:
using System.Collections;
using System.Reflection;
using Castle.DynamicProxy;
/// <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方法。
本文轉自永春部落格園部落格,原文連結:http://www.cnblogs.com/firstyi/archive/2007/09/29/910624.html,如需轉載請自行聯系原作者