配置功能是軟件必要的功能,下面介紹以下 Glacier 內置的配置框架,Glacier 支持三種方式的配置:
優先級:獨立的 HOCON 配置 > 嵌入的 HOCON 配置 > appSettings 配置
優先級高的配置會覆蓋優先級低的配置
關於 Glacier 框架使用,請前往:https://www.gkarch.com/
例如在 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();
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>;
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