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即可,不需要进行重复的、实现
有错误或者片面地方欢迎指正
赞 (0)