文章目录

1、命令行配置

2、Json文件配置

3、配置文件文本至C#对象实例的映射

4、配置文件热更新

5、总结

命令行的配置

 我们首先来创建一个.net core 的控制台项目,然后引入.net core all 包(Install-Package Microsoft.AspNetCore.All -Version 2.0.3),接下来添加系统参数。右键项目属性,调试,如下图(这里的参数为 =》name=lmc age=15):接下来,我们控制台打印一下

 static void Main(string[] args)
{
//系统参数
var builder = new ConfigurationBuilder()
.AddCommandLine(args);
var configration = builder.Build();
Console.WriteLine($"name :{configration["name"]}");
Console.WriteLine($"age :{configration["age"]}");
Console.ReadLine();
}

接下来让我们把应用程序参数删除,从内存中添加默认参数。ConfigurationBuilder对象的AddInMemoryCollection方法接收一个键值对的数组,我们这里用一个字典来初始化默认参数

         static void Main(string[] args)
{
//默认参数
var dic = new Dictionary<string, string>
{
{ "name","liumengchen"},
{ "age",""}
};
//系统参数
var builder = new ConfigurationBuilder()
.AddInMemoryCollection(dic) //从内存中加载参数配置
.AddCommandLine(args);
var configration = builder.Build();
Console.WriteLine($"name :{configration["name"]}");
Console.WriteLine($"age :{configration["age"]}");
Console.ReadLine();
}

Json文件配置

  我们在项目中添加一个"MyClass.json" 文件,ConfigurationBuilder的扩展方法AddJsonFile添加json配置文件,我们看到ConfigurationRoot的Providers中存储着json文件读取出来的数据,然后让我们来打印一下=》

             var builder = new ConfigurationBuilder()
.AddJsonFile("MyClass.json");
var configRetion = builder.Build(); Console.WriteLine($"classId:{configRetion["classId"]}"); var entitys = configRetion.Providers; Console.WriteLine("**************************指定索引打印**************************");
Console.WriteLine($"studentId:{configRetion["student:0:id"]}");
Console.WriteLine($"studentname:{configRetion["student:0:name"]}");
Console.WriteLine($"studentId:{configRetion["student:1:id"]}");
Console.WriteLine($"studentname:{configRetion["student:1:name"]}");
Console.WriteLine($"studentId:{configRetion["student:2:id"]}");
Console.WriteLine($"studentname:{configRetion["student:2:name"]}");

配置文件文本至C#对象实例的映射

  创建一个空的mvc项目,将上一步的json文件 复制到这个项目中,并且改名为appsettings.json(因为Program.cs 中  BuildWebHost方法中,默认将appsettings.json写入配置)。然后我们创建一个类,名字叫做MyClass=>

     public class MyClass
{
public string classId { get; set; }
public List<student> student { get; set; }
}
public class student
{
public int id { get; set; }
public string name { get; set; }
}

我们在Startup 中添加一个 IConfiguration,然后再构造函数中注入

     public class Startup
{
public IConfiguration configuration { get; set; }
public Startup(IConfiguration Configuration)
{
this.configuration = Configuration;
}

接下来,我们读取配置文件中的内容

         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.Run(async (context) =>
{
MyClass myClass = new MyClass();
configuration.Bind(myClass); //这里的Bind方法,将配置文件中的内容绑定到myClass实例
await context.Response.WriteAsync($"classId:{myClass.classId}");
await context.Response.WriteAsync($"studentId:{myClass.student[0].id}");
await context.Response.WriteAsync($"studentname:{myClass.student[0].name}");
await context.Response.WriteAsync($"studentId:{myClass.student[1].id}");
await context.Response.WriteAsync($"studentname:{myClass.student[1].name}");
await context.Response.WriteAsync($"studentId:{myClass.student[2].id}");
await context.Response.WriteAsync($"studentname:{myClass.student[2].name}");
});
}

接下来我们将配置文件读取到MVC的视图中去。首先添加一个Home控制器,在控制器中注入MyClass,代码修改为如下:

     public class HomeController : Controller
{
public readonly MyClass _myClass;
public HomeController(IOptions<MyClass> myClass)
{
_myClass = myClass.Value;
}
public IActionResult Index()
{
return View(_myClass);
}
}

修改我们的startup.cs 和添加Index.cshtml,将视图的model设置为MyClass

         public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyClass>(configuration); //注册IConfiguration,让控制器中IOptions读到appsettings
services.AddMvc();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvcWithDefaultRoute();//添加路由中间件
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
      }
 @model MVCConfigApplication.MyClass

 @{
ViewData["Title"] = "Index";
} <h2>Index</h2> <h4>Class Id:@Model.classId</h4> @foreach(var entity in @Model.student)
{
<ul>
<li>studentId:@entity.id</li>
<li>studentId:@entity.name</li>
</ul> }

接下来让我们来看一下结果=》

当然,我们也可以不使用控制器,在视图中直接注入MyClass。我们在HomeController中删除依赖注入的代码,修改Index.cshtml代码如下:

     public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
@using Microsoft.Extensions.Options
@inject IOptions<MVCConfigApplication.MyClass> MyClass @{
ViewData["Title"] = "Index";
} <h2>Index</h2>
<h4>Class Id:@MyClass.Value.classId</h4>
@foreach(var entity in @MyClass.Value.student)
{
<ul>
<li>studentId:@entity.id</li>
<li>studentId:@entity.name</li>
</ul> }

配置文件热更新

将IOptions 改为IOptionsSnapshot

在asp.net core 中,WebHost.CreateDefaultBuilder(args)  方法中,默认加载appsettings.json文件,并且将是否更改重新加载设置为true

这里是github webhost.cs源码:

所以我们想关闭热更新只需要将WebHost的ConfigureAppConfiguration方法中 config.AddJsonFile第三个参数设置为false就可以了。=》 config.AddJsonFile("appsettings.json", false, false);

总结一下

在框架配置中,有两个最重要的对象。第一个是IConfigurationSource,第二个是IConfigurationProvider。IConfigurationSource 在实例化 ConfigurationBuilder时候,可以把不同的Source添加至builder,例如Program中的BuildWebHost方法,最后使用生成器模式统一生成(Build),追加到IConfigurationProvider当中。读取时候,就根据IConfigurationProvider当中是否存在"Key",把对应的值读取出来。

Jesse博客学习笔记。传送门=》 http://video.jessetalk.cn/

Core篇——初探Core配置管理的更多相关文章

  1. Core篇——初探Core的认证,授权机制

    目录 1.Cookie-based认证的实现 2.Jwt Token 的认证与授权 3.Identity Authentication + EF 的认证 Cookie-based认证的实现 cooki ...

  2. Core篇——初探Core的Http请求管道&&Middleware

    目录: 1.Core 处理HTTP请求流程 2.中间件(Middleware)&&处理流程 3.创建自定义中间件&&模拟Core的请求管道 Core 处理HTTP请求流 ...

  3. Core篇——初探IdentityServer4(OpenID Connect模式)

    Core篇——初探IdentityServer4(OpenID Connect客户端验证) 目录 1.Oauth2协议授权码模式介绍2.IdentityServer4的OpenID Connect客户 ...

  4. Core篇——初探IdentityServer4(客户端模式,密码模式)

    Core篇——初探IdentityServer4(客户端模式,密码模式) 目录 1.Oatuth2协议的客户端模式介绍2.IdentityServer4客户端模式实现3.Oatuth2协议的密码模式介 ...

  5. Core篇——初探依赖注入

    目录 1.DI&&IOC简单介绍 2.UML类图中六种关联关系 3..net core 中DI的使用 4..net core DI初始化源码初窥 DI&&IOC简单介绍 ...

  6. ASP.NET Core Blazor 初探之 Blazor Server

    上周初步对Blazor WebAssembly进行了初步的探索(ASP.NET Core Blazor 初探之 Blazor WebAssembly).这次来看看Blazor Server该怎么玩. ...

  7. .net core WebAPI 初探及连接MySQL

    1. 前言 笔者最近跟着微软官方文档学习.net core WebAPI,但发现其对 WebAPI 连接数据库.读取数据库方面讲得不够细致明了.写此文的目的,即实现 .net core WebAPI ...

  8. net Core 通过 Ef Core 访问、管理Mysql

    net Core 通过 Ef Core 访问.管理Mysql 本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1. ...

  9. ABP 教程文档 1-1 手把手引进门之 ASP.NET Core & Entity Framework Core(官方教程翻译版 版本3.2.5)

    本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 官方文档分四部分 一. 教程文档 二.ABP 框架 三.zero 模块 四.其他(中文翻译资源) 本篇是第一部分的第一篇. 第一部分分三篇 1- ...

随机推荐

  1. DB2 char长度问题

    问题:发现用char转换了后的值长度都变为了11,更长的变为了254

  2. Absolute Horizontal And Vertical Centering In CSS

    Quick CSS Trick: How To Center an Object Exactly In The Center Centering in CSS: A Complete Guide Ab ...

  3. JS面向对象(1)——构造函数模式和原型模式

    1.构造函数模式 构造函数用来创建特定的类型的对象.如下所示: function Person(name,age,job){ this.name=name; this.job=job; this.ag ...

  4. Scala 技术笔记之 可变长参数

    转自 http://www.cnblogs.com/rollenholt/p/4112833.html Scala 允许你指明函数的最后一个参数可以是重复的.这可以允许客户向函数传入可变长度参数列表. ...

  5. Codeforces Round #468 (Div. 2, based on Technocup 2018 Final Round)A. Friends Meeting

    Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the ...

  6. css中的流,元素,基本尺寸

    流 元素 基本尺寸 流之所以影响整个css世界,是因为它影响了css世界的基石 --HTML HTML 常见的标签有虽然标签种类繁多,但通常我们就把它们分为两类: 块级元素(block-level e ...

  7. POJ 1258 Agri-Net( 裸最小生成树 )

    链接:传送门! 题意:一个裸最小生成树,采用Kruskal. /******************************************************************** ...

  8. [SCOI2016]萌萌哒(倍增+并查集)

    当区间\([a,b]\)和\([c,d]\)对应相等时. 我们把两个区间对应位置上的数所在并查集合并. 最后并查集的数量为\(num\)答案就是\(9*10^num\)因为是个数,不能有前置\(0\) ...

  9. nyoj13-Fibonacci数

    Fibonacci数 时间限制:3000 ms  |  内存限制:65535 KB 难度:1 描述 无穷数列1,1,2,3,5,8,13,21,34,55...称为Fibonacci数列,它可以递归地 ...

  10. BZOJ 3144 [HNOI2013]切糕 (最大流+巧妙的建图)

    题面:洛谷传送门 BZOJ传送门 最大流神题 把点权转化为边权,切糕里每个点$(i,j,k)$向$(i,j,k+1)$连一条流量为$v(i,j,k)$的边 源点$S$向第$1$层的点连边,第$R+1$ ...