早前分享過一篇關於 Castle ActiveRecord (AR) 配置的文章,那是協助一位初學 AR 的朋友完成小範例後的心得。文中採用 IConfigurationSource,將設定寫在 web.config 中。實際上,ActiveRecord 支援將配置獨立存放或動態配置,例如透過 XML 或 Hashtable。本文將補充這兩種配置方式,並介紹一種封裝配置的通用解決方案。
透過 XmlConfigurationSource 讀取外部 XML 檔案(如 AppConfig.xml)來取得配置資訊。範例如下:
<?xml version="1.0" encoding="utf-8" ?>
<activerecord>
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="hibernate.connection.connection_string" value="Data Source=.;Initial Catalog=test;Integrated Security=SSPI" />
</config>
</activerecord>
程式碼端:
XmlConfigurationSource source = new XmlConfigurationSource("../appconfig.xml");
透過 InPlaceConfigurationSource 直接在記憶體中建立配置,適合動態產生連線字串的情境:
Hashtable properties = new Hashtable();
properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver");
properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2000Dialect");
properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider");
properties.Add("hibernate.connection.connection_string", "Data Source=.;Initial Catalog=test;Integrated Security=SSPI");
InPlaceConfigurationSource source = new InPlaceConfigurationSource();
source.Add(typeof(ActiveRecordBase), properties);
上述兩種方式各有優劣。XML 需額外維護檔案,Hashtable 則便於在程式碼中動態組裝。在開發通用元件時,若每個專案都要修改 web.config 或新增 XML 檔,維護成本極高。因此設計一個封裝方法,僅需傳入資料庫名稱與實體組件,即可自動完成 ActiveRecord 初始化,大幅簡化專案啟動流程。
核心邏輯:
InPlaceConfigurationSource 註冊配置並初始化 AR。這樣新專案只需引用該通用庫,呼叫單一初始化方法即可,不再煩惱配置檔的部署與維護。