public class MyConfigClass {
public string Username {get;set }
public string Password {get;set;}
public string API {get;set;}
public int TimeOut {get;set;} = 6000;
}
You can register your options in a composer
var options = builder.Services.AddOptions<MyConfigClass>()
.Bind(builder.Config.GetSection("MyConfig"));
"MyConfig" is the name of the section in appsettings.
then you should be able to inject this as an IOptions<MyConfigClass> into any services/controllers that need to read your settings
there are other options such as IMontorOptions that mean you don't have to restart to update options. Microsoft docs has a bit more on them,.
Thank you Kevin - I did get it working just before you replied but will use your version. Hopefully the thread will help anyone else new to v9 not familiar with this. Much appreciated.
How to inject a custom configuration section?
Hi
Could anyone clarify how to create and inject your own configuration into a custom service via dependency injection please?
I'm registering a service and I need some configuration for an api key. I'm registering the service in a composer.
Then the service needs some configuration passing into the constructor
Then I have config in appsettings.json
How do you get dependency injection to pass in the config section?
I'm sure it's really obvious but complete .net core newbie.
Thanks
I think I've figured it - missing registering the configuration class.
Hi,
if you have a class that represents your options.
eg.
You can register your options in a composer
"MyConfig" is the name of the section in appsettings.
then you should be able to inject this as an
IOptions<MyConfigClass>
into any services/controllers that need to read your settingsthere are other options such as IMontorOptions that mean you don't have to restart to update options. Microsoft docs has a bit more on them,.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-5.0
Thank you Kevin - I did get it working just before you replied but will use your version. Hopefully the thread will help anyone else new to v9 not familiar with this. Much appreciated.
How would yuo access data from the appsettings in razor view?
Have tried to Inject my custom Settings models but is not working..
is working on a reply...