提供者模式的運作仰賴兩大基礎設施:強型別提供者集合與自訂配置區段。本文詳細說明 MessageProviderCollection 與 MessageProviderConfigurationSection 的設計細節。
MessageProviderCollection 繼承自 ProviderCollection,覆寫 Add 方法強制型別檢查:
public override void Add(ProviderBase provider) {
if (provider == null) throw new ArgumentNullException("provider");
if (!(provider is MessageProvider)) throw new ArgumentException("必須為 MessageProvider 型別");
base.Add(provider);
}
此設計確保集合僅包含合法提供者,避免執行期型別錯誤。
MessageProviderConfigurationSection 繼承 ConfigurationSection,定義兩個關鍵屬性:
DefaultProvider:指定預設提供者名稱。Providers:ProviderSettingsCollection 型別,儲存所有提供者設定。public class MessageProviderConfigurationSection : ConfigurationSection {
private readonly ConfigurationProperty _defaultProvider = new ConfigurationProperty("defaultProvider", typeof(string), null);
private readonly ConfigurationProperty _providers = new ConfigurationProperty("providers", typeof(ProviderSettingsCollection), null);
[ConfigurationProperty("defaultProvider")]
public string DefaultProvider { get => (string)base[_defaultProvider]; set => base[_defaultProvider] = value; }
[ConfigurationProperty("providers")]
public ProviderSettingsCollection Providers => (ProviderSettingsCollection)base[_providers];
protected override ConfigurationPropertyCollection Properties {
get {
var props = new ConfigurationPropertyCollection();
props.Add(_defaultProvider);
props.Add(_providers);
return props;
}
}
}
對應的 web.config 或 app.config 設定:
<configSections>
<section name="MessageProvider" type="Pattern.Provider.MessageProviderConfigurationSection, Pattern.Provider" />
</configSections>
<MessageProvider defaultProvider="SqlMessageProvider">
<providers>
<add name="SqlMessageProvider" type="Pattern.Provider.SqlMessageProvider, Pattern.Provider" connectionStringName="SqlConn" />
<add name="XMLMessageProvider" type="Pattern.Provider.XMLMessageProvider, Pattern.Provider" connectionStringName="XmlConn" />
</providers>
</MessageProvider>
ProvidersHelper 載入機制。這兩個類別構成提供者模式的骨幹,使動態載入與切換成為可能。