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 每次更改配置都会从新加载,不须要从新启动项目。 } }