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 每次更改配置都会重新加载,不需要重新启动项目。
}
}
参考资料:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix