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

参考资料:

最新文章

  1. Python JPype 在 Win7 下安装与使用
  2. MyBatis源码分析(1)——整体依赖关系图
  3. extjs组件添加事件监听的三种方式
  4. 用Access作为后台数据库支撑。
  5. DP+单调队列 codevs 1748 瑰丽华尔兹(还不是很懂具体的代码实现)
  6. 鼠标经过容器放大--css3
  7. BZOJ 1199: [HNOI2005]汤姆的游戏 计算几何暴力
  8. (转)validateRequest=&quot;false&quot;
  9. Linux查找yum安装软件在系统中路径
  10. Unity中的关节
  11. &lt;a href=&#39;javascript:void(0)&#39; onclick=&#39;my()&#39;&gt;&lt;/a&gt;
  12. coreGraphs和动画
  13. poj1151 Atlanis 线段树+离散化求矩形面积的并
  14. PAT1070:Mooncake
  15. 「POI2011 R2 Day2」Tree Rotations【线段树合并】
  16. 【转】QPainter中坐标系变换问题
  17. css第二天
  18. python不要使用可变对象作为参数的默认值
  19. SDN竞赛思考总结
  20. tomcat启动窗口中的时间与系统时间不一致

热门文章

  1. servlet cdi注入
  2. Vue Loader
  3. 微信小程序 支付功能 服务器端(TP5.1)实现
  4. .net core 微服务之日志落盘设计
  5. ssh服务器配置
  6. SQLyog简介及其功能(附百度云盘下载地址)
  7. cdnbest架设cdn同一个源用不同的端口访问如何设置
  8. matplotlib坐标轴的一些操作
  9. GCD - Extreme (II) (欧拉函数妙用)
  10. salt-api配置安装 以及使用