DotNetCore cross-platform ~ Customize configuration items in etettings. json,
Back to directory
In DotNetCore, everything is dependent on injection. For the Scalable configuration object of appsettings, it is located in the project root directory and is generally registered in startup, in the class, we can get the current object through constructor injection to use it. Of course, we can also build and use it on our own. I will summarize it below.
Traditional method, startup injection, and constructor
1. Pay attention to the configuration class.
Public class RedisConfiguration {# region attribute member /// <summary> // File Upload path /// </summary> public string Host {get; set ;} /// <summary> /// format of the file to be uploaded /// </summary> public string Password {get; set ;} /// <summary> /// maximum size of Image Upload KB /// </summary> public int IsProxy {get; set ;}# endregion}
2. Add its content to the deleettings.
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "RedisConfiguration": { "Host": "localhost:6379", "Password": "bobo123#", "IsProxy": "0" }}
3. Use it in the Controller. Of course, you can define its usage in the base class, but the injection entry is still in the constructor method.
public class ApiControllerBase : Controller { private readonly IOptions<RedisConfiguration> AppConfiguration; public ApiControllerBase(IOptions<RedisConfiguration> appConfiguration) { AppConfiguration = appConfiguration; } }
At this time, your AppConfiguration has a value after it is loaded. It is injected during the program running!
Property injection and use
The content of appsetting remains unchanged. It only encapsulates the process of configuration injection and acquisition in attributes. Note that you can create and obtain it as a singleton to consider performance, I will not design this point!
public RedisConfiguration AppConfigurations { get { var config = new ConfigurationBuilder() .AddInMemoryCollection() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); var sp = new ServiceCollection().AddOptions().Configure<RedisConfiguration>( config.GetSection("RedisConfiguration")).BuildServiceProvider(); var _appConfiguration = sp.GetService<IOptions<RedisConfiguration>>(); return _appConfiguration.Value; } }
You can use it directly on the controller. This attribute is implemented on the parent class of all controllers.
[HttpGet] public IEnumerable<string> Get() { return new string[] { AppConfigurations.Host, AppConfigurations.Password, AppConfigurations.IsProxy.ToString() }; }
Thank you for reading this article!
We are still researching. net core. We hope that core2.0 and standard2.0 will not disappoint us!
I heard that it has implemented all. net frameworks 4.6.1 functions!
Back to directory