1. 程式人生 > >ASP.NET Core 配置文件(無處不在的依賴註入)

ASP.NET Core 配置文件(無處不在的依賴註入)

word gist .net core closed 數據 minus [] etsec 過程

前煙:

  .NET Core 中取消了以往的 XML 節點配置文件,改用了 *.json 格式。

  在 Startup.cs 文件中,構造方法 build appsetting.json 文件,

  本文主要對解析配置文件的官方工具類做總結;

一、appsettings.json 文件

  在新建的 Core Web 項目中,默認會有一個全局的配置變量:IConfigurationRoot

  提供了索引器、GetSection 方法;

{
  "Host": "http://localhost:5966/",
  "Title": "Hello World",
  
"SiteKeywords": "asp.net, c#, asp.net core, asp.net entityframework core", "Description": "DotNetClub: asp.net core", "ConnectionString": "Data Source=localhost;Initial Catalog=dbName;User Id=userName;Password=pwd;", "Redis": { "EndPoints": [ "localhost", "6379" ], "Password": ""
, "Db": "" }, "Site": { "Host": "http://localhost:5966", "Title": "Hello World", "Description": "DotNetClub: asp.net core", "AllowRegister": true, "VerifyRegisterUser": false, "AdminUserList": [] }, "CookieName": "DotNetClub.User", "Categories": [ {
"Key": "share", "Name": "分享" }, { "Key": "ask", "Name": "問答" }, { "Key": "job", "Name": "招聘" } ] }

  獲取根節點數據:

  Configuration["ConnectionString"]

  Configuration["Title"]

  獲取節點數據:

  services.Configure<RedisOptions>(Configuration.GetSection("Redis").Bind)

  重點記錄的是這個 Microsoft.Extensions.Options.ConfigurationExtensions 提供的 IOptions

  Configure 方法可以將 appsettings.json 中的配置綁定某一個實體對象上。如:

技術分享
    public class RedisOptions
    {
        /// <summary>
        /// Redis end points, such as "{host or ip}:{port}"
        /// </summary>
        public string[] EndPoints { get; set; }

        /// <summary>
        /// Redis password
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// Default redis database
        /// </summary>
        public int Db { get; set; }
    }
View Code

  完成這樣的一個過程就是 Configure 類實現了一個依賴註入;

ASP.NET Core 配置文件(無處不在的依賴註入)