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 ...
随机推荐
- github简单使用教程(转)
github是一个基于git的代码托管平台,付费用户可以建私人仓库,我们一般的免费用户只能使用公共仓库,也就是代码要公开.对于一般人来说公共仓库就已经足够了,而且我们也没多少代码来管理,O(∩_∩)O ...
- TortoiseGit小乌龟 git管理工具
1.新建分支git远端新建分支: b001本地git目录:右击--TortoiseGit--获取(会获取到新建分支) 2.本地新建分支对应远端分支本地新建分支:b001 关联远端分支b001(之后工作 ...
- Linux-Shell脚本编程-学习-7-总结前面开启后面的学习
国庆前期后国庆回来也都比较忙,把书一放下,在那起来,就难了,发现好多都开始忘记了,今天好不容易硬着头片看来两章,算是马马虎虎的把前面的基础性质的只是看完了吧. 后面讲开始学习Shell编程的高级阶段, ...
- 《python核心编程第二版》第2章习题
2-1 略 2-1 略 2-2 (a)打印 结果是9 (b)9 (c)一样 (d)略 (e)略 2-3 略 2-4 (a) # /usr/bin/pythonraw_input() (b) # /us ...
- 【java并发编程实战】第七章:取消与关闭
停止线程的几种方式 一般的逻辑停止 public class ThreadInterruptTest { public static volatile boolean cancel = true; p ...
- NLP系列-中文分词(基于统计)
上文已经介绍了基于词典的中文分词,现在让我们来看一下基于统计的中文分词. 统计分词: 统计分词的主要思想是把每个词看做是由字组成的,如果相连的字在不同文本中出现的次数越多,就证明这段相连的字很有可能就 ...
- VC++之运算符重载简单小结
封装继承和多态是面向对象三大基本支柱.在面向对象系统中有两种编译方式:静态联编和动态联编静态联编:也叫早期联编:指系统在编译时就决定如何实现某一动作,提供了执行速度快的优点.动态联编:也叫滞后联编:指 ...
- mongodb数据库高级操作
1.创建索引 2.索引名称 3.其他索引 4.explain 5.操作索引 6.高级特性 7.固定集合 8.导入导出 9.上锁 10.添加用户 11.主从复制
- KMP板子+Trie板子
KMP算法是一个字符串匹配算法,最直白的用法就是在一个长度为n的字符串T中查找另一个长度为m字符串P的匹配(总之就是用于文本中进行单个字符串的匹配). 对于这个问题,暴力算法是很好做的,直接对于T的每 ...
- 并查集——hdu1213(入门)
传送门:How Many Tables 模板代入 判断几个连通分支 DFS亦可完成 [并查集] #include <iostream> #include <cstdio> #i ...