C# 中的应用配置

配置功能是软件必要的功能,下面介绍以下 Glacier 内置的配置框架,Glacier 支持三种方式的配置:

  • appSettings 配置
  • 嵌入的 HOCON 配置
  • 独立的 HOCON 配置

优先级:独立的 HOCON 配置 > 嵌入的 HOCON 配置 > appSettings 配置

优先级高的配置会覆盖优先级低的配置

关于 Glacier 框架使用,请前往:https://www.gkarch.com/

1 appSetting 配置

例如在 appSetting 中存在以下配置

<configuration>
  <appSettings>
    <add key="prefix:key1" value="42" />
    <add key="prefix:key2" value="foo,bar" />
    <add key="prefix:key3:innerKey" value="hello world" />
  </appSettings>
</configuration>

通过 Glacier 框架,可以通过使用如下代码来获取配置(可以直接通过 As.. 转换成具体的类型)

// 程序启动时,添加需要加载的配置前缀:
GlacierSystem.Core.AddAppSettingsConfig("prefix");

// 需要获取配置时:
var config = GlacierSystem.Core.GetConfig("prefix");
var val1 = config["key1"].AsInt();
var val2 = config["key2"].AsList<string>();

var innerVal = config["key3:innerKey"].AsString();
//
var innerVal = config.GetSub("key3")["innerKey"].AsString();

2 嵌入的 HOCON 配置

HOCON 方式的配置支持类型绑定功能,可以直接将配置绑定到具体的类,使配置更具可读性,方便使用和管理。

依然利用之前的例子,这次使用嵌入的 HOCON 配置

<configuration>
  <configSections>
    <section name="glacier"
             type="GKarch.Glacier.Configuration.HoconSection, GKarch.Glacier" />
  </configSections>
  <glacier>
    <![CDATA[
prefix {
  key1 = 42
  key2 = [foo, bar]
  key3 = {
    innerKey = "hello world"
  }
}
]]>
  </glacier>
</configuration>

定义一个类来对应这个配置:

// 自定义模型
class MyConfig
{
    public int Key1 { get; set; }
    public IList<string> Key2 { get; set; }
    public IDictionary<string, string> Key3 { get; set; }
}

读取配置并绑定到模型

// 获取配置并绑定到自定义模型
MyConfig config = GlacierSystem.Core.GetConfig("prefix").Bind<MyConfig>;

3 独立的 HOCON 配置

HOCON 配置可以是独立的配置文件,通过独立的配置文件可以更方便的进行开发环境和生产环境的切换,

首先在 appSetting 中定义配置文件

<configuration>
  <appSettings>
    <add key="glacier:config:provider" value="hocon" />
    <!-- 默认加载 config.conf 文件,需要使用其他文件名可添加如下配置 -->
    <!-- <add key="glacier:config:hocon:file" value="my.conf" /> -->
  </appSettings>
</configuration>

config.conf 配置文件内容

prefix {
  key1 = 42
  key2 = [foo, bar]
  key3 = {
    innerKey = "hello world"
  }
}

这次使用一个嵌套的类型来对应配置,定义如下两个类来对应配置

class MyConfig
{
    public int Key1 { get; set; }
    public IList<string> Key2 { get; set; }
    public MyInnerConfig Key3 { get; set; }
}

class MyInnerConfig
{
    public string InnerKey { get; set; }
}

读取配置

var config = GlacierSystem.Core.GetConfig("prefix").Bind<MyConfig>();
Console.WriteLine(config.Key3.InnerKey);  // hello world
posted @ 2016-08-15 10:25  firslien  阅读(1661)  评论(0编辑  收藏  举报