DotNETCore 学习笔记 配置
- Configuration
- var builder = new ConfigurationBuilder();
- builder.AddInMemoryCollection();
- var config = builder.Build();
- config["somekey"] = "somevalue";
- // do some other work
- var setting = config["somekey"]; // also returns "somevalue"
- {
- "ConnectionStrings": {
- "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Debug",
- "System": "Information",
- "Microsoft": "Information"
- }
- }
- }
- // work with with a builder using multiple calls
- var builder = new ConfigurationBuilder();
- builder.SetBasePath(Directory.GetCurrentDirectory());
- builder.AddJsonFile("appsettings.json");
- var connectionStringConfig = builder.Build();
- // chain calls together as a fluent API
- var config = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .AddEntityFrameworkConfig(options =>
- options.UseSqlServer(connectionStringConfig.GetConnectionString("DefaultConnection"))
- )
- .Build();
- public Startup(IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
- if (env.IsDevelopment())
- {
- // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
- builder.AddUserSecrets();
- }
- builder.AddEnvironmentVariables();
- Configuration = builder.Build();
- }
- public static void Main(string[] args)
- {
- var builder = new ConfigurationBuilder();
- Console.WriteLine("Initial Config Sources: " + builder.Sources.Count());
- builder.AddInMemoryCollection(new Dictionary<string, string>
- {
- { "username", "Guest" }
- });
- Console.WriteLine("Added Memory Source. Sources: " + builder.Sources.Count());
- builder.AddCommandLine(args);
- Console.WriteLine("Added Command Line Source. Sources: " + builder.Sources.Count());
- var config = builder.Build();
- string username = config["username"];
- Console.WriteLine($"Hello, {username}!");
- }
- -----------------------------------------------------------------------------------------
- Using Options and configuration objects
- public class MyOptions
- {
- public string Option1 { get; set; }
- public int Option2 { get; set; }
- }
- public class HomeController : Controller
- {
- private readonly IOptions<MyOptions> _optionsAccessor;
- public HomeController(IOptions<MyOptions> optionsAccessor)
- {
- _optionsAccessor = optionsAccessor;
- }
- // GET: /<controller>/
- public IActionResult Index() => View(_optionsAccessor.Value);
- }
- public void ConfigureServices(IServiceCollection services)
- {
- // Setup options with DI
- services.AddOptions();
- // Configure MyOptions using config by installing Microsoft.Extensions.Options.ConfigurationExtensions
- services.Configure<MyOptions>(Configuration);
- // Configure MyOptions using code
- services.Configure<MyOptions>(myOptions =>
- {
- myOptions.Option1 = "value1_from_action";
- });
- // Configure MySubOptions using a sub-section of the appsettings.json file
- services.Configure<MySubOptions>(Configuration.GetSection("subsection"));
- // Add framework services.
- services.AddMvc();
- }
- ---------------------------------------------------------------------------------------
- Writing custom providers
- public class ConfigurationValue
- {
- public string Id { get; set; }
- public string Value { get; set; }
- }
- public class ConfigurationContext : DbContext
- {
- public ConfigurationContext(DbContextOptions options) : base(options)
- {
- }
- public DbSet<ConfigurationValue> Values { get; set; }
- }
- public class EntityFrameworkConfigurationSource : IConfigurationSource
- {
- private readonly Action<DbContextOptionsBuilder> _optionsAction;
- public EntityFrameworkConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)
- {
- _optionsAction = optionsAction;
- }
- public IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- return new EntityFrameworkConfigurationProvider(_optionsAction);
- }
- }
- public class EntityFrameworkConfigurationProvider : ConfigurationProvider
- {
- public EntityFrameworkConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
- {
- OptionsAction = optionsAction;
- }
- Action<DbContextOptionsBuilder> OptionsAction { get; }
- public override void Load()
- {
- var builder = new DbContextOptionsBuilder<ConfigurationContext>();
- OptionsAction(builder);
- using (var dbContext = new ConfigurationContext(builder.Options))
- {
- dbContext.Database.EnsureCreated();
- Data = !dbContext.Values.Any()
- ? CreateAndSaveDefaultValues(dbContext)
- : dbContext.Values.ToDictionary(c => c.Id, c => c.Value);
- }
- }
- private static IDictionary<string, string> CreateAndSaveDefaultValues(
- ConfigurationContext dbContext)
- {
- var configValues = new Dictionary<string, string>
- {
- { "key1", "value_from_ef_1" },
- { "key2", "value_from_ef_2" }
- };
- dbContext.Values.AddRange(configValues
- .Select(kvp => new ConfigurationValue { Id = kvp.Key, Value = kvp.Value })
- .ToArray());
- dbContext.SaveChanges();
- return configValues;
- }
- }
- public static class EntityFrameworkExtensions
- {
- public static IConfigurationBuilder AddEntityFrameworkConfig(
- this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> setup)
- {
- return builder.Add(new EntityFrameworkConfigurationSource(setup));
- }
- }
- using System;
- using System.IO;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- namespace CustomConfigurationProvider
- {
- public static class Program
- {
- public static void Main()
- {
- // work with with a builder using multiple calls
- var builder = new ConfigurationBuilder();
- builder.SetBasePath(Directory.GetCurrentDirectory());
- builder.AddJsonFile("appsettings.json");
- var connectionStringConfig = builder.Build();
- // chain calls together as a fluent API
- var config = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .AddEntityFrameworkConfig(options =>
- options.UseSqlServer(connectionStringConfig.GetConnectionString("DefaultConnection"))
- )
- .Build();
- Console.WriteLine("key1={0}", config["key1"]);
- Console.WriteLine("key2={0}", config["key2"]);
- Console.WriteLine("key3={0}", config["key3"]);
- }
- }
- }
DotNETCore 学习笔记 配置的更多相关文章
- Docker学习笔记 — 配置国内免费registry mirror
Docker学习笔记 — 配置国内免费registry mirror Docker学习笔记 — 配置国内免费registry mirror
- blfs(systemd版本)学习笔记-配置远程访问和管理lfs系统
我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 要实现远程管理和配置lfs系统需要配置以下软件包: 前几页章节脚本的配置:https://www.cnblogs.com/ren ...
- blfs(systemv版本)学习笔记-配置远程访问和管理lfs系统
我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 要实现远程管理和配置lfs系统需要配置以下软件包: 前几页章节脚本的配置:https://www.cnblogs.com/ren ...
- Dubbo -- 系统学习 笔记 -- 配置
Dubbo -- 系统学习 笔记 -- 目录 配置 Xml配置 属性配置 注解配置 API配置 配置 Xml配置 配置项说明 :详细配置项,请参见:配置参考手册 API使用说明 : 如果不想使用Spr ...
- Dubbo -- 系统学习 笔记 -- 配置参考手册
Dubbo -- 系统学习 笔记 -- 目录 配置参考手册 <dubbo:service/> <dubbo:reference/> <dubbo:protocol/> ...
- Linux学习笔记 | 配置ssh
目录: SSH的必要性 将默认镜像源修改为清华镜像源 Linux安装ssh软件 使用putty软件实现ssh连接 Windows下安装winscp SSH的必要性 一般服务器都位于远程而非本地,或者及 ...
- oracle学习笔记——配置环境
题记:最近再学oracle,于是按照这本经典的书<Oracle Database 9i/10g/11g编程艺术>来学习. 配置环境 如何正确建立SCOTT/TIGER演示模式 需要建立和运 ...
- Entity Framework学习笔记——配置EF
初次使用Entity Framework(以下简称EF),为了避免很快忘记,决定开日志记录学习过程和遇到的问题.因为项目比较小,只会用到EF的一些基本功能,因此先在此处制定一个学习目标:1. 配置EF ...
- Xamarin 学习笔记 - 配置环境(Windows & iOS)
本文翻译自CodeProject文章:https://www.codeproject.com/Articles/1223980/Xamarin-Notes-Set-up-the-environment ...
随机推荐
- jmeter添加自定义扩展函数之图片base64编码
打开eclipse,新建maven工程,在pom中引入jmeter核心jar包: <!-- https://mvnrepository.com/artifact/org.apache.jmete ...
- 基于jersey和Apache Tomcat构建Restful Web服务(一)
基于jersey和Apache Tomcat构建Restful Web服务(一) 现如今,RESTful架构已然成为了最流行的一种互联网软件架构,它结构清晰.符合标准.易于理解.扩展方便,所以得到越来 ...
- 常用模块(xml)
XML(可扩展性标记语言)是一种非常常用的文件类型,主要用于存储和传输数据.在编程中,对XML的操作也非常常见. 本文根据python库文档中的xml.etree.ElementTree类来进行介绍X ...
- ISAP 最大流 最小割 模板
虽然这道题用最小割没有做出来,但是这个板子还是很棒: #include<stdio.h> #include<math.h> #include<string.h> # ...
- 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 ...
- css制作环形文本
css制作环形文本 在项目开发中,我们可能会遇到环形文本的需求,这个时候,怎样在代码以通俗易懂的前提下实现我们需要的效果呢?可能你会想到用一个一个的span元素计算出旋转的角度然后拼接起来,这个方案不 ...
- PHP+IIS上传大文件
最近刚接触IIS服务器,在使用php上传大文件的时候,遇到了一些问题.通过查阅网上资料进行了总结,希望对各位有帮助. 第一步,检查PHP的配置. 打开php.ini配置文件 1.file_upload ...
- C#数据库连接问题
最近在看C#,今天下午刚开始接触C#的数据库连接,SQL Server2008,问题如图:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名 ...
- 集显也能硬件编码:Intel SDK && 各种音视频编解码学习详解
http://blog.sina.com.cn/s/blog_4155bb1d0100soq9.html INTEL MEDIA SDK是INTEL推出的基于其内建显示核心的编解码技术,我们在播放高清 ...
- zufe 蓝桥选拔
https://zufeoj.com/contest.php?cid=1483 问题 A: A 代码: #include <bits/stdc++.h> using namespace s ...