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 ...
随机推荐
- This content database has a schema version which is not supported in this farm.
I want to move the website to another server. The new server has reinstall Sharepoint2013 serv ...
- 纯原生仿ES6的Object.assign,实现深度合并对象
源码: function isObj(x){ var type = typeof x; return x !== null && (type === 'object' || type ...
- 零基础学习Vim编辑器
**********************************************************************0.这篇教程的简介:Vim是Linux/Unix下的经典编辑 ...
- Linux-Qt Quick学习1-Hello world
Qt作为共平台的开发IDE.实在是强大,在Quick的学习中,与平台无关,我这里使用ubuntu和openSUSE,之所以不用Windows,是因为我想借这个机会过学习一点linux的东西,哪怕是熟悉 ...
- Leetcode代码补全——链表
通过补全代码可以更深刻的体会到,链表就是一个存储方式,通过一单元的存储指向下一单元,而查看单元内容通过头部开始的指针依次遍历.这是leetcode里融合两个链表的题目,具体代码如下: #encodin ...
- CentOs 版本名字说明
What images are in this directory CentOS-6.3-x86_64-netinstall.iso This is the network install and r ...
- CSP201604-1:折点计数
引言:CSP(http://www.cspro.org/lead/application/ccf/login.jsp)是由中国计算机学会(CCF)发起的"计算机职业资格认证"考试, ...
- zabbix从入门到精通
第1章 zabbix监控 1.1 为什么要监控 在需要的时刻,提前提醒我们服务器出问题了 当出问题之后,可以找到问题的根源 网站/服务器 的可用性 1.1.1 网站可用性 在软件系统的高可靠性(也 ...
- 山科 STUST OJ Problem B: 编写函数:String to Double (II) (Append Code)
这道题没啥别的毛病,我的错误在于看不懂题. 另外还有一点是注意浮点数存在-0 #include <stdio.h> #include <ctype.h> #include &l ...
- OJ题归纳
1.求最大公约数 利用辗转相除法求最大公约数 int gcd(int a,int b) { int c,r; if(a<b){c=a;a=b;b=c;} if(b==0) return a; r ...