First of all, to understand the configuration in Core, please click here to learn about it:https:///article/
1. Option interface
There are three option interfaces in Core, namely:
IOptions<TOptions>
IOptionsSnapshot<TOptions>
IOptionsMonitor<TOptions>
All three methods can obtain configurations, the difference is life cycle and file monitoring.
2. Inject configuration and IOptions
First we create a Core API project and add a file with the following content:
{ "Title": "test", "Name": "Test Test" }
Create another model class corresponding to it:
public class TestModel { public string Title { get; set; } public string Name { get; set; } }
Then at StartupConfigureServices
Added to the method:
<TestModel>(new ConfigurationBuilder().AddJsonFile("").Build());
This will automatically inject the configuration service. So how do we receive this configuration?
We can use it firstIOptions<T>
Come and receive.
Add a controller with the name as follows:
public class TestController : ControllerBase { private readonly TestModel _options; public TestController(IOptions<TestModel> options) { _options = ; } }
This allows you to receive access configurations.
This isIOptions<TOptions>
Use of .
IOptions<TOptions>
It has the following characteristics:
Not supported:
- Read configuration data after the application is started.
- Naming Options
Can:
- Register as a single instance and can be injected into any service lifetime.
That is, the configuration file generation object (single instance) is read before the application is started. Of course, if the configuration file (.json) is modified in the future, it will not affect this object.
3,IOptionsSnapshot
Document Explanation: By usingIOptionsSnapshot<TOptions>
, When requesting lifetime access and cache options, the option is calculated once per request.
The life scope of IOptionsSnapshot is scoped, which is valid for a request cycle.
Others remain unchanged, when used:
private readonly TestModel _options; public TestController(IOptionsSnapshot<TestModel> options) { _options = ; }
Since IOptionsSnapshot is updated every time it is requested, updates can be obtained in time after the configuration file is changed.
IOptionsMonitor is slightly different:
public class TestController : ControllerBase { private readonly IOptionsMonitor<TestModel> _options; public TestController(IOptionsMonitor<TestModel> options) { _options = options; } [HttpGet("T")] public ContentResult T() { return new ContentResult() { Content = _options. }; } }
Both IOptionsSnapshot and IOptionsMonitor can detect changes in configuration files, but IOptionsSnapshot is a new object every time I request it, while IOptionsMonitor is singleton mode.
This is all about this article about the Core option interface. I hope it will be helpful to everyone's learning and I hope everyone will support me more.