在IBatis.Net中可以通過配置文件動態選擇數據庫、動態選擇Dao對象。
Dao對象也就是操作數據庫的類,通過配置文件我們可以選擇DataMapper的方式、Ado的方式、NHibernet的方式以前其他第三方的方式來操作數據庫。有利於系統的靈活性和可擴展性。
通過分析動態選擇Dao的設計可以加深對IBatis.Net的理解,更好的使用它,同時也可以借鑒它的好的設計模式,應用到我們的程序開發中去。
源代碼是最好的分析方式,下面是一些重點代碼和說明:
前提:需要在dao.config中配置:
<daoFactory>
<dao interface="GSpring.Dao.Interfaces.IAccountDao, GSpring.Dao" implementation="GSpring.Dao.Implementations.AccountDao, GSpring.Dao"/>
</daoFactory>
在代碼中首先需要進行初始化:
DomDaoManagerBuilder builder = new DomDaoManagerBuilder();
builder.Configure("dao.config");
這段代碼實際上做瞭很多事情,其中就有:將所有的配置的dao的接口和實現註冊到DaoManager類的靜態屬性中去。也就是在整個應用程序或網站啟動時註冊一次就可以瞭,以後直接從靜態屬性中取出來使用就可以瞭。
和dao註冊相關的代碼如下:
dao.Implementation = NodeUtils.GetStringAttribute(prop, "implementation");
dao.Interface = NodeUtils.GetStringAttribute(prop, "interface");
_daoInstance = _daoImplementation.GetConstructor(Type.EmptyTypes).Invoke(null) as IDao;
_proxy = DaoProxy.NewInstance(this);
也就是把配置文件中的interface和implementation讀取,然後生成代理。
最主要的就是最後一句代碼,DaoProxy.NewInstance的實現如下:
Castle.DynamicProxy.ProxyGenerator proxyGenerator = new ProxyGenerator();
IInterceptor handler = new DaoProxy(dao);
Type[] interfaces = {dao.DaoInterface, typeof(IDao)};
return (proxyGenerator.CreateProxy(interfaces, handler, dao.DaoInstance) as IDao);
這裡我們看到其中使用瞭Castle.DynamicProxy中的方法(Castle是另外一個開源框架,我和在以後的博客中再說)
DaoProxy實現IInterceptor接口,也就是AOP中常有的攔截機。以後當我們通過IDao接口調用實際的Dao時,都會先通過DaoProxy,由DaoProxy攔截後進行一些必要的處理,然後再動態決定調用哪一個Dao來進行數據庫操作
生成好之後都會放在DaoManager的靜態屬性中,下次要用的時候直接從裡面去就可以瞭:
public IDao this[Type daoInterface]
{
get
{
Dao dao = _daoMap[daoInterface] as Dao;
if (dao == null)
{
throw new DataException("There is no DAO implementation found for " + daoInterface.Name + " in this context.");
}
IDao idao = dao.Proxy;
return idao;
}
}
以上涉及到的主要的類圖如下:
作者 awp110