App.Config文件復(fù)雜對象自動映射
Nerdle.AutoConfig 是什么
.Net Framework 使用 app.config XML文件作為默認(rèn)的配置文件, visual studio也提供很方便的配置管理功能, 甚至可以自動將配置項映射到 Settings 類, 但這僅限于簡單的數(shù)據(jù)類型, 比如 string/int 等. 對于復(fù)雜類型, 需要我們自己寫映射代碼才行.
Nerdle.AutoConfig 實(shí)現(xiàn)了通用的復(fù)雜類型配置映射功能, 擴(kuò)展性很好, 能適應(yīng)不同配置需求.
使用步驟
- 在代碼中定義配置類接口, 注意是 interface.
- 在程序初始化時, 完成XML文件和配置類接口的綁定.
- 在app.config XML文件
增加一個 , 明確后續(xù)自定義配置項名稱和Nerdle AutoConfig處理類. - 在app.config XML文件中增加自定義的配置.
注意事項
- 接口成員變量首字母可以大寫也可以小寫, 但 Xml 中的 tag 和 attribute 必須是小寫, 否則無法完成映射
- 接口成員變量默認(rèn)都需要在Xml中設(shè)置, 如果xml不設(shè)置, 成員變量需要增加 [DefaultValue] 特性
- 類中可定義 IEnumerable<> 類型成員, xml 中需要有子tag集合對應(yīng).
- 類中可定義 IDictionary<> 類型成員, xml 中需要有子tag集合對應(yīng), 每個 XML 子 tag 必須提供 key 和 value attribute4
代碼示例
- app.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- 在app.config XML文件 <configSections> 增加 <section>, 明確后續(xù)自定義配置項名稱和Nerdle AutoConfig處理類. -->
<section name="turboConfiguration" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<!-- 在app.config XML文件中增加自定義的配置. -->
<turboConfiguration>
<defaultProfileName>dev</defaultProfileName>
<nameMapping>
<anyTag key="1" value="A" />
<anyTag key="2" value="B" />
</nameMapping>
<turboProfiles>
<turboProfile>
<profileName>dev</profileName>
<webPort>8080</webPort>
</turboProfile>
<turboProfile>
<profileName>production</profileName>
<webPort>80</webPort>
</turboProfile>
</turboProfiles>
</turboConfiguration>
</configuration>
- 配置接口定義
/// <summary>
///在代碼中定義配置類接口, 注意是 interface.
/// </summary>
public interface ITurboConfiguration
{
IEnumerable<ITurboProfile> TurboProfiles { get; }
string defaultProfileName { get; }
[DefaultValue("no input")]
string details { get; }
IDictionary<string, string> nameMapping { get; }
}
/// <summary>
/// 在代碼中定義配置類接口, 注意是 interface.
/// </summary>
public interface ITurboProfile
{
string ProfileName { get; }
int webPort { get; }
}
- XML文件和配置接口的綁定代碼
/// <summary>
/// 在程序初始化時, 完成XML文件和配置類接口的綁定.
/// </summary>
private void loadXmlConfig()
{
ITurboConfiguration xmlConfig = Nerdle.AutoConfig.AutoConfig.Map<ITurboConfiguration>();
}

浙公網(wǎng)安備 33010602011771號