Skip to content

5. 自定义Section格式

Emrys edited this page Jan 25, 2018 · 1 revision

1. 原始配置文件Section有可能存在的不必要的操作

在原始的配置文件中,我们需要自定义配置文件,那么就需要在配置文件中配置section,如我们常见的EntityFramework。

如果我们自定义配置文件位置,也就说不用原始的配置文件,那么我们也就没必要按照之前的配置方法每次在configSections新建一个Section,然后在配置。

2. 解决办法,我们所需要的配置文件

<?xml version="1.0" encoding="utf-8" ?> 
<config>
  <userInfo userName="CEmrys" email="i@emrys.me" age="17">
    <blogUrl>http://www.cnblogs.com/emrys5/</blogUrl>
    <favoriteColor>Blue</favoriteColor>
    <dislikeColor>2</dislikeColor>
  </userInfo>
  <arrayString>
    <item>a</item>
    <item>b</item>
    <item>c</item>
    <item>d</item>
    <item>e</item>
  </arrayString>
</config>

如文件位置在/Cfg/SetSection.config,在自定义Section中,必须指定文件路径,因为原始的配置文件不支持自定义Section格式。

3. 设置

var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cfg", "SetSection.config");

SuperConfig<UserInfo>.Setting(configFilePath, (sectionName, filePath, convertCaseStrategy) =>
{
    XElement xElement = XElement.Load(filePath);
    var caseSectionName = convertCaseStrategy.ConvertCase(sectionName);
    var sectionElement = xElement.Elements().Where(i => i.Name == caseSectionName).FirstOrDefault();
    if (sectionElement == null)
    {
        throw new Exception("dot find section:" + sectionName);
    }

    return new Section() { XElement = sectionElement };
});

分析代码

void Setting(string filePath, Func<string, string, IConvertCaseStrategy, Section> funcSection)

SuperConfig的Setting方法第一个参数需要一个filePath,第二个参数是一个两个String和IConvertCaseStrategy作为参数返回值为Section的委托。

委托中,第一个参数为sectionName,第二个参数为filePath,第三个参数为IConvertCaseStrategy(也就是命名规则,可以调用方法ConvertCase获取转换后的名称),然后返回Section值,也就是说只要赋值Section的属性XElement即可。

4. 一个Section一个配置文件

我们也可能遇到一个配置文件就对应一个实体对象,不存在多个Section,一个Section也就是一个配置文件,比如有人喜欢把不同的配置分成不同的配置文件。

4.1 Config

<?xml version="1.0" encoding="utf-8" ?>
<userInfo userName="SUEmrys" email="i@emrys.me" age="17">
  <blogUrl>http://www.cnblogs.com/emrys5/</blogUrl>
  <favoriteColor>Blue</favoriteColor>
  <dislikeColor>2</dislikeColor>
</userInfo> 

4.2 设置

var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cfg", "SectionUserInfo.config");

SuperConfig<UserInfo>.Setting(configFilePath, (sectionName, filePath, convertCaseStrategy) =>
{
     return new Section() { XElement = XElement.Load(filePath) };
});

4.3 获取值

var user = SuperConfig<UserInfo>.Value;
Assert.AreEqual(user.UserName, "SUEmrys");

Clone this wiki locally