下面的代码演示了如何在.NET Core中使用“内存配置”:
/// <summary> /// 获取格式设置 /// </summary> /// <returns></returns> public static FormatSettings GetFormatSettings() { // Key使用冒号:分隔路径,实现层级化 Dictionary<string, string> initialData = new Dictionary<string, string> { // 时间格式化 ["Format:DateTime:LongDatePattern"] = "dddd, MMMM d, yyyy", ["Format:DateTime:LongTimePattern"] = "h:mm:ss tt", ["Format:DateTime:ShortDatePattern"] = "M/d/yyyy", ["Format:DateTime:ShortTimePattern"] = "h:mm tt", // 金额格式化 ["Format:CurrencyDecimal:Digits"] = "2", ["Format:CurrencyDecimal:Symbol"] = "$", }; var source = new MemoryConfigurationSource { InitialData = initialData }; IConfiguration configuration = new ConfigurationBuilder() .Add(source) .Build().GetSection("Format"); IOptions<FormatSettings> optionsAccessor = new ServiceCollection() .AddOptions() .Configure<FormatSettings>(configuration) .BuildServiceProvider() .GetService<IOptions<FormatSettings>>(); FormatSettings settings = optionsAccessor.Value; return settings; } /// <summary> /// 格式设置类 /// </summary> public class FormatSettings { public DateTimeFormatSettings DateTime { get; set; } public CurrencyDecimalFormatSettings CurrencyDecimal { get; set; } } /// <summary> /// 时间格式化设置 /// </summary> public class DateTimeFormatSettings { public string LongDatePattern { get; set; } public string LongTimePattern { get; set; } public string ShortDatePattern { get; set; } public string ShortTimePattern { get; set; } } /// <summary> /// 货币格式化设置 /// </summary> public class CurrencyDecimalFormatSettings { public int Digits { get; set; } public string Symbol { get; set; } }