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 ... 
随机推荐
- 【APUE】Chapter16 Network IPC: Sockets & makefile写法学习
			16.1 Introduction Chapter15讲的是同一个machine之间不同进程的通信,这一章内容是不同machine之间通过network通信,切入点是socket. 16.2 Sock ... 
- XPivot 用户手册及版本更新公示
			此文仅介绍XPivot的通用功能,如有对项目中定制的高级功能感兴趣的可留言讨论 XPivot当前版本v2.2 [2015-04-20发布] v2.1 下载链接: http://pan.baidu.co ... 
- 【个人训练】(UVa11129)An antiarithmetic permutation
			题意与解析 一条非常有趣的二分题.一开始没有懂解法,去网上看了半天全是做法没有这样做为什么是对的(或者说的很含糊).一做完回顾一下立刻有点开朗的感觉. 题意很简单,维护一个0-n-1的数列,使其选出长 ... 
- CF 55D
			Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer numb ... 
- C++STL——概述
			一.相关介绍 STL 标准模板库 在编写代码的过程中有一些程序经常会被用到,而且需求特别稳定,所以C++中把这些常用的模板做了统一的规范,慢慢的就形成了STL 提供三种类型的组件: 容器.迭代器和算法 ... 
- 【iOS开发】NSOperation简单介绍
			iOS开发多线程篇—NSOperation简单介绍 一.NSOperation简介 1.简单说明 NSOperation的作⽤:配合使用NSOperation和NSOperationQueue也能实现 ... 
- HTML5表单提交与PHP环境搭建
			PHP服务器使用xampp集成套件 路径 D:\xampp\htdocs\MyServer\index.php 访问 http://localhost/MyServer/index.php 能够正常显 ... 
- 【bzoj1257】[CQOI2007]余数之和sum  数论
			题目描述 给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 + … + k mod n的值,其中k mod i表示k除以i的余数.例如j(5, 3)=3 m ... 
- [luogu P1442] 铁球落地
			题目链接 线段树\(+dp\). 先用线段树预处理出每个线段从左边和右边掉落到哪里,记为\(f[i][0/1]\). 然后记\(g[i][0/1]\)为到达第\(i\)个线段的左边或右边所要的最小时间 ... 
- [洛谷P2044][NOI2012]随机数生成器
			题目大意:给你$m,a,c,X_0,n,g$,求$X_{n+1}=(a\cdot X_n+c) \bmod{m}$,最后输出对$g$取模 题解:矩阵快速幂+龟速乘,这里用了$long\;double$ ... 
