App.Config文件复杂对象自动映射

发布时间 2023-12-24 19:32:16作者: harrychinese

Nerdle.AutoConfig 是什么

.Net Framework 使用 app.config XML文件作为默认的配置文件, visual studio也提供很方便的配置管理功能, 甚至可以自动将配置项映射到 Settings 类, 但这仅限于简单的数据类型, 比如 string/int 等. 对于复杂类型, 需要我们自己写映射代码才行.

Nerdle.AutoConfig 实现了通用的复杂类型配置映射功能, 扩展性很好, 能适应不同配置需求.

使用步骤

  1. 在代码中定义配置类接口, 注意是 interface.
  2. 在程序初始化时, 完成XML文件和配置类接口的绑定.
  3. 在app.config XML文件 增加一个
    , 明确后续自定义配置项名称和Nerdle AutoConfig处理类.
  4. 在app.config XML文件中增加自定义的配置.

注意事项

  1. 接口成员变量首字母可以大写也可以小写, 但 Xml 中的 tag 和 attribute 必须是小写, 否则无法完成映射
  2. 接口成员变量默认都需要在Xml中设置, 如果xml不设置, 成员变量需要增加 [DefaultValue] 特性
  3. 类中可定义 IEnumerable<> 类型成员, xml 中需要有子tag集合对应.
  4. 类中可定义 IDictionary<> 类型成员, xml 中需要有子tag集合对应, 每个 XML 子 tag 必须提供 key 和 value attribute4

代码示例

  1. app.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<!-- 在app.config XML文件 <configSections> 增加 <section>, 明确后续自定义配置项名称和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>
  1. 配置接口定义
    /// <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; }
    }
  1. XML文件和配置接口的绑定代码

        /// <summary>
        /// 在程序初始化时, 完成XML文件和配置类接口的绑定. 
        /// </summary>
        private void loadXmlConfig()
        {
            ITurboConfiguration xmlConfig = Nerdle.AutoConfig.AutoConfig.Map<ITurboConfiguration>();
        }