文章出處

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 每次更改配置都會重新加載,不需要重新啟動項目。
    }
}

參考資料:


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()