首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 提供者模式實作第五部分:提供者集合與配置區段詳細解析

     編輯:關於C語言

提供者基礎設施:集合類別與配置區段實作

提供者模式的運作仰賴兩大基礎設施:強型別提供者集合與自訂配置區段。本文詳細說明 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>

關鍵設計要點

  1. 型別安全:集合層級攔截非法型別。
  2. 配置解耦:提供者實作細節完全由配置決定。
  3. 標準遵循:遵循 ASP.NET 提供者模式標準架構,相容 ProvidersHelper 載入機制。

這兩個類別構成提供者模式的骨幹,使動態載入與切換成為可能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved