博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
DotNETCore 学习笔记 配置
阅读量:6120 次
发布时间:2019-06-21

本文共 6326 字,大约阅读时间需要 21 分钟。

Configurationvar builder = new ConfigurationBuilder();builder.AddInMemoryCollection();var config = builder.Build();config["somekey"] = "somevalue";// do some other workvar 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 callsvar builder = new ConfigurationBuilder();builder.SetBasePath(Directory.GetCurrentDirectory());builder.AddJsonFile("appsettings.json");var connectionStringConfig = builder.Build();// chain calls together as a fluent APIvar 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
{ { "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 objectspublic class MyOptions{ public string Option1 { get; set; } public int Option2 { get; set; }}public class HomeController : Controller{ private readonly IOptions
_optionsAccessor; public HomeController(IOptions
optionsAccessor) { _optionsAccessor = optionsAccessor; } // GET: /
/ 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
(Configuration); // Configure MyOptions using code services.Configure
(myOptions => { myOptions.Option1 = "value1_from_action"; }); // Configure MySubOptions using a sub-section of the appsettings.json file services.Configure
(Configuration.GetSection("subsection")); // Add framework services. services.AddMvc();}---------------------------------------------------------------------------------------Writing custom providerspublic class ConfigurationValue{ public string Id { get; set; } public string Value { get; set; }}public class ConfigurationContext : DbContext{ public ConfigurationContext(DbContextOptions options) : base(options) { } public DbSet
Values { get; set; }}public class EntityFrameworkConfigurationSource : IConfigurationSource { private readonly Action
_optionsAction; public EntityFrameworkConfigurationSource(Action
optionsAction) { _optionsAction = optionsAction; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new EntityFrameworkConfigurationProvider(_optionsAction); } } public class EntityFrameworkConfigurationProvider : ConfigurationProvider { public EntityFrameworkConfigurationProvider(Action
optionsAction) { OptionsAction = optionsAction; } Action
OptionsAction { get; } public override void Load() { var builder = new DbContextOptionsBuilder
(); 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
CreateAndSaveDefaultValues( ConfigurationContext dbContext) { var configValues = new Dictionary
{ { "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
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"]); } }}

 

转载于:https://www.cnblogs.com/ziranquliu/p/5871976.html

你可能感兴趣的文章
MS SQLSERVER通用存储过程分页
查看>>
60.使用Azure AI 自定义视觉服务实现物品识别Demo
查看>>
Oracle 冷备份
查看>>
jq漂亮实用的select,select选中后,显示对应内容
查看>>
C 函数sscanf()的用法
查看>>
python模块之hashlib: md5和sha算法
查看>>
linux系统安装的引导镜像制作流程分享
查看>>
解决ros建***能登录不能访问内网远程桌面的问题
查看>>
pfsense锁住自己
查看>>
vsftpd 相关总结
查看>>
bash complete -C command
查看>>
解决zabbix 3.0中1151端口不能运行问题
查看>>
售前工程师的成长---一个老员工的经验之谈
查看>>
Get到的优秀博客网址
查看>>
dubbo
查看>>
【Git入门之四】操作项目
查看>>
老男孩教育每日一题-第107天-简述你对***的理解,常见的有哪几种?
查看>>
Python学习--time
查看>>
在OSCHINA上的第一篇博文,以后好好学习吧
查看>>
高利率时代的结局,任重道远,前途叵测
查看>>