Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binding options inside other options services.Configure<>()

Imagine I have the following settings in appsettings.json :

  {
  "OtherSettings" : {
    "id" : 3
  },
  
  "Needed" : {
    "Database" : {
      "ConnectionString" : "abc123"
    },

    "Interval" : {
      "is_active" = true,
      "in_seconds" = "15" 
    }
  } 
}

For the Database section I’ve got an class which is DatabaseSettings with property ConnectionString.

And for the Interval section I’ve got the class IntervalSettings.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I would like to bind all those settings inside Needed to an class NeededSettings, what property do I need and how would I bind the options for the Database class with Dependency Injection ? Currently I am doing this with:

services.Configure<DatabaseSettings>Configuration.GetSection("Needed:Database"));
services.Configure<IntervalSettings>(Configuration.GetSection("Needed:Interval"));

So I am doing this with 2 lines, but I want to do it in 1 line and bind all the settings to the new class NeededSettings

>Solution :

Simply remove these two lines and add:

services.Configure<NeededSettings>(Configuration.GetSection("Needed"));

and use NeededSettings in all places you used DatabaseSettings and IntervalSetttings.

Edit:

public class NeededSettings{
    public DatabaseSettings Database {get;set;}
    public IntervalSettings Interval {get;set;}
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading