ASP.NET Core 設定檔(無處不在的依賴注入)

來源:互聯網
上載者:User

標籤:key   pass   .json   設定檔   ati   roo   view   sof   .net   

前煙:

  .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 設定檔(無處不在的依賴注入)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.