I need to read a list of properties from appsettings.json
file (section: placeto
) in a business class, but I haven't been able to access them. I need these properties to be public.
I add the file in the Program
class:
This is my appsettings.json
:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"placeto": {
"login": "fsdfsdfsfddfdfdfdf",
"trankey": "sdfsdfsdfsdfsdf"
}
}
First : Use the default in
program.cs
for it already adds Configuration:Second : Create an Interface for your class and pass configuration with dependency injection by creating
Iconfiguration
field:then pass it by contructor:
Then create an interface for your class in order to use
Dependency Injection
properly. Then one can create instances of it without needing to passIConfiguration
to it.Here is the class and Interface:
Third: Then in your startup.cs implement Dependency Injection for your class by calling:
in your
ConfigureServices
methodNow you can pass your class instances to any class used by Dependency Injection too.
For example, if you have
ExampleController
that you wanna use your class within do the following:And now you have _test instance to access it anywhere in your controller.