.NetCore讀取配置Json文件到類中並在程序使用


ConfigurationBuilder 這個類提供了配置綁定,在dnc中 Program中WebHost提供了默認的綁定(appsettings文件)

如果我們需要加載我們自己的json配置文件怎么處理

 var builder = new ConfigurationBuilder();

這里builder 提供了很多添加的方式

1、第一種:直接添加json文件路徑,這里需要注意的json文件地址問題

  builder.AddJsonFile("path").Build();

2、第二種

  builder.Add("IConfigurationSource的實例")
builder.Add(new JsonConfigurationSource { Path = "WebSiteConfig.json", Optional = false, ReloadOnChange = true }).Bind();

配置好了 建立對應的json文件對應的實體模型類

在服務里面配置一下:

services.Configure<WebSiteConfig>(Configuration);//配置

比如數據庫連接字符串的配置處理,或者系統中的固定配置,這里我擴展了下 NPoco的服務擴展添加

services.AddNPocoContext(options =>
            {
                options.connectionstring = Configuration.Get<WebSiteConfig>().ConnectionStr;

            });

在系統中業務層或者其他層次怎么來獲取這個配置

這里需要用的一個接口IOptions

在服務中添加注入下相關類

services.AddOptions();

 

比如在我們的測試類中注入相關IOptions的模型類

private IOptions<NPocoDataBaseSetting> _options;
        private IOptions<WebSiteConfig> _website;
        private ITestRepository _testservices;
        private ITransaction _transaction;
        public TestServices(IServiceProvider serviceProvider, IOptions<NPocoDataBaseSetting> options, ITransaction transaction, IOptions<WebSiteConfig> website, ITestRepository testservices)
        {
            _options = options;
            _testservices = testservices;
            _transaction = transaction;
            _website = website;
        }

如:

IOptions<WebSiteConfig> _website ,我們可以通過
  /// <summary>
        /// 測試獲取數據
        /// </summary>
        /// <returns></returns>
        public List<Test> getdata()
        {
            string webname = _website.Value.WebName;
            List<Test> list = new List<Test>();
            try
            {
                _transaction.Begin();
               
                list = _testservices.test();
                _transaction.Commit();

            }
            catch (Exception)
            {
                _transaction.RollBack();

            }
            return list;

        }

獲取到webname,這里值得注意的json文件中文亂碼問題,要確定好json文件的編碼類型 UTF-8

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM