星空网 > 软件开发 > ASP.net

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




原标题:C# 中的应用配置

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

欧美再次爆发疫情、暴乱,亚马逊中国卖家该如何应对黑五网一?:https://www.ikjzd.com/articles/133341
美国大选,对跨境电商都有哪些影响?:https://www.ikjzd.com/articles/133342
全球速卖通打破跨境壁垒,开启2020年双十一全球购物节:https://www.ikjzd.com/articles/133343
小白开启亚马逊之路需要做什么:https://www.ikjzd.com/articles/133344
跨境电商刷单被罚14万,这才是全国首例:https://www.ikjzd.com/articles/133346
运营阿里巴巴国际站让我学会无数技能:https://www.ikjzd.com/articles/133347
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流