每天記錄一點:NetCore獲得設定檔 appsettings.json

來源:互聯網
上載者:User

標籤:erp   sql   path   ice   net   mysql資料庫   service   orm   hang   

用NetCore做項目如果用EF  ORM在網上有很多的配置連接字串,讀取以及使用方法

由於很多朋友用的其他ORM如SqlSugar,NH,Dapper等,在讀取連接字串的時候,往往把資訊儲存到一個設定檔中,例如appsetting.json,

網上有很多關於讀取appsetting.json都是通過注入的方式,  在ORM讀取配置的時候,都是在一個類庫裡面,所以用注入的方式有時候不適合【個人理解】

 

因以上情境,下面這個方法讀取配置可以在任何地方使用

 

喜歡NetCore的朋友,歡迎加群QQ:86594082

源碼後續補上

 

1、在項目中,建立一個NetCore的類庫,建立類ConfigServices

namespace Core.Extensions{    /// <summary>    /// 讀取設定檔    /// </summary>    public class ConfigServices    {        public static IConfiguration Configuration { get; set; }        static ConfigServices()        {            //ReloadOnChange = true 當appsettings.json被修改時重新載入                        Configuration = new ConfigurationBuilder()            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })            .Build();        }    }}

2、在Web項目下面appsettings.json裡面增加自訂的配置

{  "DBConnection": {    "MySqlConnectionString": "server=localhost;database=fyt_ims;uid=root;pwd=123456;charset=‘utf8‘;SslMode=None"  },    "Logging": {    "IncludeScopes": false,    "LogLevel": {      "Default": "Warning"    }  }}

 

3、建立一個讀取配置的類

namespace FytErp.Core.Model.ConfigModel{    /// <summary>    /// 資料庫連接字串    /// </summary>    public class DBConnection    {        /// <summary>        /// MySql資料庫連接字串        /// </summary>        public string MySqlConnectionString { get; set; }        /// <summary>        /// SqlServer資料庫連接字串        /// </summary>        public string SqlServerConnectionString { get; set; }    }}

 

4、編寫測試讀取配置

namespace FytErp.Web.Pages{    public class IndexModel : PageModel    {        public DbConnection DbSetting { get; private set; }        public void OnGet()        {            //獲得設定檔中的DBConnection節點            DbSetting = ConfigServices.Configuration.GetSection("DbConnection").Get<DbConnection>();        }    }}

 

5、最終讀取結果

 

每天記錄一點:NetCore獲得設定檔 appsettings.json

相關關鍵詞:
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.