1. Configuration
  2.  
  3. var builder = new ConfigurationBuilder();
  4. builder.AddInMemoryCollection();
  5. var config = builder.Build();
  6. config["somekey"] = "somevalue";
  7.  
  8. // do some other work
  9.  
  10. var setting = config["somekey"]; // also returns "somevalue"
  11.  
  12. {
  13. "ConnectionStrings": {
  14. "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  15. },
  16. "Logging": {
  17. "IncludeScopes": false,
  18. "LogLevel": {
  19. "Default": "Debug",
  20. "System": "Information",
  21. "Microsoft": "Information"
  22. }
  23. }
  24. }
  25.  
  26. // work with with a builder using multiple calls
  27. var builder = new ConfigurationBuilder();
  28. builder.SetBasePath(Directory.GetCurrentDirectory());
  29. builder.AddJsonFile("appsettings.json");
  30. var connectionStringConfig = builder.Build();
  31.  
  32. // chain calls together as a fluent API
  33. var config = new ConfigurationBuilder()
  34. .SetBasePath(Directory.GetCurrentDirectory())
  35. .AddJsonFile("appsettings.json")
  36. .AddEntityFrameworkConfig(options =>
  37. options.UseSqlServer(connectionStringConfig.GetConnectionString("DefaultConnection"))
  38. )
  39. .Build();
  40.  
  41. public Startup(IHostingEnvironment env)
  42. {
  43. var builder = new ConfigurationBuilder()
  44. .SetBasePath(env.ContentRootPath)
  45. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  46. .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
  47.  
  48. if (env.IsDevelopment())
  49. {
  50. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
  51. builder.AddUserSecrets();
  52. }
  53.  
  54. builder.AddEnvironmentVariables();
  55. Configuration = builder.Build();
  56. }
  57.  
  58. public static void Main(string[] args)
  59. {
  60. var builder = new ConfigurationBuilder();
  61. Console.WriteLine("Initial Config Sources: " + builder.Sources.Count());
  62.  
  63. builder.AddInMemoryCollection(new Dictionary<string, string>
  64. {
  65. { "username", "Guest" }
  66. });
  67.  
  68. Console.WriteLine("Added Memory Source. Sources: " + builder.Sources.Count());
  69.  
  70. builder.AddCommandLine(args);
  71. Console.WriteLine("Added Command Line Source. Sources: " + builder.Sources.Count());
  72.  
  73. var config = builder.Build();
  74. string username = config["username"];
  75.  
  76. Console.WriteLine($"Hello, {username}!");
  77. }
  78. -----------------------------------------------------------------------------------------
  79. Using Options and configuration objects
  80. public class MyOptions
  81. {
  82. public string Option1 { get; set; }
  83. public int Option2 { get; set; }
  84. }
  85.  
  86. public class HomeController : Controller
  87. {
  88. private readonly IOptions<MyOptions> _optionsAccessor;
  89.  
  90. public HomeController(IOptions<MyOptions> optionsAccessor)
  91. {
  92. _optionsAccessor = optionsAccessor;
  93. }
  94.  
  95. // GET: /<controller>/
  96. public IActionResult Index() => View(_optionsAccessor.Value);
  97. }
  98.  
  99. public void ConfigureServices(IServiceCollection services)
  100. {
  101. // Setup options with DI
  102. services.AddOptions();
  103.  
  104. // Configure MyOptions using config by installing Microsoft.Extensions.Options.ConfigurationExtensions
  105. services.Configure<MyOptions>(Configuration);
  106.  
  107. // Configure MyOptions using code
  108. services.Configure<MyOptions>(myOptions =>
  109. {
  110. myOptions.Option1 = "value1_from_action";
  111. });
  112.  
  113. // Configure MySubOptions using a sub-section of the appsettings.json file
  114. services.Configure<MySubOptions>(Configuration.GetSection("subsection"));
  115.  
  116. // Add framework services.
  117. services.AddMvc();
  118. }
  119.  
  120. ---------------------------------------------------------------------------------------
  121.  
  122. Writing custom providers
  123.  
  124. public class ConfigurationValue
  125. {
  126. public string Id { get; set; }
  127. public string Value { get; set; }
  128. }
  129. public class ConfigurationContext : DbContext
  130. {
  131. public ConfigurationContext(DbContextOptions options) : base(options)
  132. {
  133. }
  134.  
  135. public DbSet<ConfigurationValue> Values { get; set; }
  136. }
  137.  
  138. public class EntityFrameworkConfigurationSource : IConfigurationSource
  139. {
  140. private readonly Action<DbContextOptionsBuilder> _optionsAction;
  141.  
  142. public EntityFrameworkConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)
  143. {
  144. _optionsAction = optionsAction;
  145. }
  146.  
  147. public IConfigurationProvider Build(IConfigurationBuilder builder)
  148. {
  149. return new EntityFrameworkConfigurationProvider(_optionsAction);
  150. }
  151. }
  152.  
  153. public class EntityFrameworkConfigurationProvider : ConfigurationProvider
  154. {
  155. public EntityFrameworkConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
  156. {
  157. OptionsAction = optionsAction;
  158. }
  159.  
  160. Action<DbContextOptionsBuilder> OptionsAction { get; }
  161.  
  162. public override void Load()
  163. {
  164. var builder = new DbContextOptionsBuilder<ConfigurationContext>();
  165. OptionsAction(builder);
  166.  
  167. using (var dbContext = new ConfigurationContext(builder.Options))
  168. {
  169. dbContext.Database.EnsureCreated();
  170. Data = !dbContext.Values.Any()
  171. ? CreateAndSaveDefaultValues(dbContext)
  172. : dbContext.Values.ToDictionary(c => c.Id, c => c.Value);
  173. }
  174. }
  175.  
  176. private static IDictionary<string, string> CreateAndSaveDefaultValues(
  177. ConfigurationContext dbContext)
  178. {
  179. var configValues = new Dictionary<string, string>
  180. {
  181. { "key1", "value_from_ef_1" },
  182. { "key2", "value_from_ef_2" }
  183. };
  184. dbContext.Values.AddRange(configValues
  185. .Select(kvp => new ConfigurationValue { Id = kvp.Key, Value = kvp.Value })
  186. .ToArray());
  187. dbContext.SaveChanges();
  188. return configValues;
  189. }
  190. }
  191. public static class EntityFrameworkExtensions
  192. {
  193. public static IConfigurationBuilder AddEntityFrameworkConfig(
  194. this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> setup)
  195. {
  196. return builder.Add(new EntityFrameworkConfigurationSource(setup));
  197. }
  198. }
  199.  
  200. using System;
  201. using System.IO;
  202. using Microsoft.EntityFrameworkCore;
  203. using Microsoft.Extensions.Configuration;
  204.  
  205. namespace CustomConfigurationProvider
  206. {
  207. public static class Program
  208. {
  209. public static void Main()
  210. {
  211. // work with with a builder using multiple calls
  212. var builder = new ConfigurationBuilder();
  213. builder.SetBasePath(Directory.GetCurrentDirectory());
  214. builder.AddJsonFile("appsettings.json");
  215. var connectionStringConfig = builder.Build();
  216.  
  217. // chain calls together as a fluent API
  218. var config = new ConfigurationBuilder()
  219. .SetBasePath(Directory.GetCurrentDirectory())
  220. .AddJsonFile("appsettings.json")
  221. .AddEntityFrameworkConfig(options =>
  222. options.UseSqlServer(connectionStringConfig.GetConnectionString("DefaultConnection"))
  223. )
  224. .Build();
  225.  
  226. Console.WriteLine("key1={0}", config["key1"]);
  227. Console.WriteLine("key2={0}", config["key2"]);
  228. Console.WriteLine("key3={0}", config["key3"]);
  229. }
  230. }
  231. }

DotNETCore 学习笔记 配置的更多相关文章

  1. Docker学习笔记 — 配置国内免费registry mirror

    Docker学习笔记 — 配置国内免费registry mirror Docker学习笔记 — 配置国内免费registry mirror

  2. blfs(systemd版本)学习笔记-配置远程访问和管理lfs系统

    我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 要实现远程管理和配置lfs系统需要配置以下软件包: 前几页章节脚本的配置:https://www.cnblogs.com/ren ...

  3. blfs(systemv版本)学习笔记-配置远程访问和管理lfs系统

    我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 要实现远程管理和配置lfs系统需要配置以下软件包: 前几页章节脚本的配置:https://www.cnblogs.com/ren ...

  4. Dubbo -- 系统学习 笔记 -- 配置

    Dubbo -- 系统学习 笔记 -- 目录 配置 Xml配置 属性配置 注解配置 API配置 配置 Xml配置 配置项说明 :详细配置项,请参见:配置参考手册 API使用说明 : 如果不想使用Spr ...

  5. Dubbo -- 系统学习 笔记 -- 配置参考手册

    Dubbo -- 系统学习 笔记 -- 目录 配置参考手册 <dubbo:service/> <dubbo:reference/> <dubbo:protocol/> ...

  6. Linux学习笔记 | 配置ssh

    目录: SSH的必要性 将默认镜像源修改为清华镜像源 Linux安装ssh软件 使用putty软件实现ssh连接 Windows下安装winscp SSH的必要性 一般服务器都位于远程而非本地,或者及 ...

  7. oracle学习笔记——配置环境

    题记:最近再学oracle,于是按照这本经典的书<Oracle Database 9i/10g/11g编程艺术>来学习. 配置环境 如何正确建立SCOTT/TIGER演示模式 需要建立和运 ...

  8. Entity Framework学习笔记——配置EF

    初次使用Entity Framework(以下简称EF),为了避免很快忘记,决定开日志记录学习过程和遇到的问题.因为项目比较小,只会用到EF的一些基本功能,因此先在此处制定一个学习目标:1. 配置EF ...

  9. Xamarin 学习笔记 - 配置环境(Windows & iOS)

    本文翻译自CodeProject文章:https://www.codeproject.com/Articles/1223980/Xamarin-Notes-Set-up-the-environment ...

随机推荐

  1. jmeter添加自定义扩展函数之图片base64编码

    打开eclipse,新建maven工程,在pom中引入jmeter核心jar包: <!-- https://mvnrepository.com/artifact/org.apache.jmete ...

  2. 基于jersey和Apache Tomcat构建Restful Web服务(一)

    基于jersey和Apache Tomcat构建Restful Web服务(一) 现如今,RESTful架构已然成为了最流行的一种互联网软件架构,它结构清晰.符合标准.易于理解.扩展方便,所以得到越来 ...

  3. 常用模块(xml)

    XML(可扩展性标记语言)是一种非常常用的文件类型,主要用于存储和传输数据.在编程中,对XML的操作也非常常见. 本文根据python库文档中的xml.etree.ElementTree类来进行介绍X ...

  4. ISAP 最大流 最小割 模板

    虽然这道题用最小割没有做出来,但是这个板子还是很棒: #include<stdio.h> #include<math.h> #include<string.h> # ...

  5. HDU 4719 Oh My Holy FFF(DP+线段树)(2013 ACM/ICPC Asia Regional Online ―― Warmup2)

    Description N soldiers from the famous "*FFF* army" is standing in a line, from left to ri ...

  6. css制作环形文本

    css制作环形文本 在项目开发中,我们可能会遇到环形文本的需求,这个时候,怎样在代码以通俗易懂的前提下实现我们需要的效果呢?可能你会想到用一个一个的span元素计算出旋转的角度然后拼接起来,这个方案不 ...

  7. PHP+IIS上传大文件

    最近刚接触IIS服务器,在使用php上传大文件的时候,遇到了一些问题.通过查阅网上资料进行了总结,希望对各位有帮助. 第一步,检查PHP的配置. 打开php.ini配置文件 1.file_upload ...

  8. C#数据库连接问题

    最近在看C#,今天下午刚开始接触C#的数据库连接,SQL Server2008,问题如图:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名 ...

  9. 集显也能硬件编码:Intel SDK && 各种音视频编解码学习详解

    http://blog.sina.com.cn/s/blog_4155bb1d0100soq9.html INTEL MEDIA SDK是INTEL推出的基于其内建显示核心的编解码技术,我们在播放高清 ...

  10. zufe 蓝桥选拔

    https://zufeoj.com/contest.php?cid=1483 问题 A: A 代码: #include <bits/stdc++.h> using namespace s ...