netcore 非注入全局获取配置文件
在netcore开发中,最常见的就是注入,比如想获取appsettings.json的内容,我们就需要去注入,然后在controller里面去获取,但是我们如果想要在service中使用appsettings.json的内容,这样就是一个问题,并且每个controller去注入也是非常麻烦的事情
下面的注入的(这种方法百度一下可以出来几百条相同的搜索结果。。。参见https://www.cnblogs.com/ideacore/p/6282926.html)
services.AddOptions(); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
然后获取使用
我想要在service类库里面使用,这时该如何使用哪?
直接上代码:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "AppSettings": { "TestString": "This is default environment", "ConfigVersion": "local", "connectionString": "connectionString", "RedisExchangeHosts": "RedisExchangeHosts" } }
public class AppSettings { public string TestString { get; set; } public string ConfigVersion { get; set; } public string connectionString { get; set; } public string RedisExchangeHosts { get; set; } public string UploadPath { get; set; } }
public Startup(IConfiguration configuration, ILoggerFactory factory, IHostingEnvironment env) { EnvironmentName = env.EnvironmentName; Configuration = configuration; // 将内置的日志组件设置为 NHibernate 的日志组件 var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)//增加环境配置文件,新建项目默认有 .AddEnvironmentVariables(); new AppSettingProvider().Initial(configuration); Configuration = builder.Build(); }
public class AppSettingProvider { private static AppSettings _myappSettings; public static AppSettings _appSettings { get { return _myappSettings; } } public void Initial(IConfiguration configuration) { _myappSettings = new AppSettings() { ConfigVersion = configuration["AppSettings:ConfigVersion"], connectionString = configuration["AppSettings:connectionString"], TestString = configuration["AppSettings:TestString"], RedisExchangeHosts = configuration["AppSettings:RedisExchangeHosts"], UploadPath = configuration["AppSettings:UploadPath"] }; } }
这样,我们在要使用的时候只需要AppSettingProvider._appSettings.xxxx即可,不需要进行重复的、实现
有错误或者片面地方欢迎指正
作者: spatxos
出处:https://www.cnblogs.com/spatxos/p/12700974.html
版权:本站使用「spatxos」创作共享协议,未经作者同意,请勿转载;若经同意转载,请在文章明显位置注明作者和出处。
标签:
appsettings.json
, netcore
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!