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

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

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

appsettings.json示例代碼:app

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

對應AppSettings對象代碼:dom

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

    public string SecretKey { get; set; }

    public string Bucket { get; set; }

    public string Domain { get; set; }
}

ConfigureServices添加配置代碼:ide

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 每次更改配置都會從新加載,不須要從新啓動項目。
    }
}
相關文章
相關標籤/搜索