ASP.NET Core 注入和获取 AppSettings 配置
2017-04-27 19:47
911 查看
ASP.NET Core 项目中有个
实现方式就是利用 ASP.NET Core DI,将配置信息注入到 IoC 中,通过构造函数获取注入的对象。
对应
参考资料:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
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 每次更改配置都会重新加载,不需要重新启动项目。 } }
参考资料:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
相关文章推荐
- asp.net core 获取 appsettings.json 配置
- 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
- ASP.NET Core 配置文件(无处不在的依赖注入)
- ASP.NET Core读取appsettings.json的配置
- ASP.NET Core DI 手动获取注入对象
- [C#]使用 C# 代码实现拓扑排序 dotNet Core WEB程序使用 Nginx反向代理 C#里面获得应用程序的当前路径 关于Nginx设置端口号,在Asp.net 获取不到的,解决办法 .Net程序员 初学Ubuntu ,配置Nignix 夜深了,写了个JQuery的省市区三级级联效果
- IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题
- ASP.NET Core开发-获取所有注入(DI)服务
- ASP.NET core Web中使用appsettings.json配置文件的方法
- asp.net core 读取appsettings.json配置项
- Asp.net Core Startup Class中是如何获取配置信息的
- asp.net core 如何在Controller获取配置文件的值
- 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
- ASP.Net Core 2.0 获取Json和Xml格式的配置信息
- ASP.NET Core读取appsettings.json的配置
- ASP.NET Core 在 JSON 文件中配置依赖注入
- 详解ASP.NET Core 在 JSON 文件中配置依赖注入
- ASP.NET Core 1.0 Configuration 配置管理
- ASP.NET Core中的依赖注入(5): ServiceProvider实现揭秘 【解读ServiceCallSite 】
- ASP.NET Core中的依赖注入(3): 服务的注册与提供