ASP.NET Core 注入和獲取 AppSettings 配置


ASP.NET Core 項目中有個appsettings.json配置文件,用於存放一些配置信息,比如數據庫連接字符串等,但訪問的話,只能在 ASP.NET Core 項目中獲取,如果我們在其他項目類庫中,該怎樣獲取呢?

實現方式就是利用 ASP.NET Core DI,將配置信息注入到 IoC 中,通過構造函數獲取注入的對象。

appsettings.json示例代碼:

{
  "AppSettings": {
    "AccessKey": "111111",
    "SecretKey": "22222",
    "Bucket": "3333333",
    "Domain": "http://wwww.domain.com"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Error",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

對應AppSettings對象代碼:

public class AppSettings
{
    public string AccessKey { get; set; }

    public string SecretKey { get; set; }

    public string Bucket { get; set; }

    public string Domain { get; set; }
}

ConfigureServices添加配置代碼:

public void ConfigureServices(IServiceCollection services)
{
    var appSettings = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettings);
    services.AddTransient<IUpoladService, UpoladService>();

    // Add framework services.
    services.AddMvc();
}

UpoladService通過構造函數方式獲取注入對象:

public class UpoladService : IUpoladService
{
    private AppSettings _appSettings;

    public UpoladService(IOptionsMonitor<AppSettings> appSettings)
    {
        _appSettings = appSettings.CurrentValue; //IOptions 需要每次重新啟動項目加載配置,IOptionsMonitor 每次更改配置都會重新加載,不需要重新啟動項目。
    }
}

參考資料:


免責聲明!

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



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