.net core 學習筆記(5)-設定檔讀取

來源:互聯網
上載者:User

標籤:app   virt   str   configure   readonly   return   prot   資訊   pre   

1.在appsetting下新增一個配置節點:

"KeyStrings": {    "key": "abc",    "value": "test"  },

2.新增類檔案 KeyStrings.cs

public class KeyStrings{  public string key{get;set}  public string value{get;set;}    }

3.添加讀取設定檔的類及介面檔案KeyReposiroty.cs,IKeyRepository.cs

public class KeyReposiroty:IKeyReposiroty{  protected readonly   KeyStrings _keystrings;  public KeyReposiroty(IOptions<KeyStrings> keystrings){    _keystrings=keystrings  }  public virtual KeyStrings MyKeyStrings        {            get            {                               return _keystrings;            }        }        }

  

public interface IKeyReposiroty{   KeyStrings MyKeyStrings{get;}               }

  

4.新增擴充方法

public static IServiceCollection GetKeyString(this IServiceCollection services, IConfigurationSection configuration)        {                      services.Configure<KeyStrings>(configuration);            services.AddSingleton<IKeyRepository,KeyRepository>(); //無介面的時候進行類的注入:services.AddSingleton<KeyRepository>();
        return services;
    }

5.在Startup中調用擴充方法進行依賴注入  

public void ConfigureServices(IServiceCollection services){         
services.GetKeyString(Configuration.GetSection("KeyStrings"));
}

6.現在通過IkeyRepository的MyKeyStrings就能訪問到設定檔中配置節點的資訊  

  

 

.net core 學習筆記(5)-設定檔讀取

聯繫我們

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