In the development of netcore, the most common thing is injection. For example, if we want to get the content of appsettings.json, we need to inject it, and then get it in the controller. But if we want to use the content of appsettings.json in the service, this is a problem, and it is a very troublesome thing for every controller to inject it
The following injection (this method Baidu can come out hundreds of the same search results... See also https://www.cnblogs.com/ideacore/p/6282926.html)
services.AddOptions(); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Then get the use
I want to use it in the service class library. How to use it?
Direct code:
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; // Set the built-in log component to NHibernate Log component of var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)//Add environment configuration file. The default value of new project is .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"] }; } }
In this way, when we want to use it, we only need appsettingprovider. \
You are welcome to correct any mistake or one sidedness