What to pass as parameter for ConfigurationSection class in ASP.NET Core

I am using ASP.NET Core Web API(.Net-6 version).To access a Connection string, I need to configure services in Program.cs as below

enter image description here
But, While creating an Instance I need to pass a parameter. Because ConfigurationSection Has a constructor as below.

enter image description here

The problem is I dont know what to pass as parameter.
It Requires - Configuration root and path to the section.
I dont know what it is!
please help.
Thanks in advance.


Solution 1:

If it's just for get the connection string, yo can do that in you Program.cs class :

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));

And in you appsettings.json, you need somthings like that :

{
   /* ... */
   "ConnectionStrings": {
      "DefaultConnection": "you connection string"
   },
   /* ... */
}

Edit : Here a complet example of a more complicated Settings class.

The EmailSettings.cs class :

namespace MyNameSpace.Configurations
{
    public class EmailSettings
    {
        public string Host { get; set; }
        public int Port { get; set; }
        public bool EnableSSL { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

The corresponding part in the appsettings.json file:

"EmailSettings": {
    "Host": "smtp.gmail.com",
    "Port": 587,
    "EnableSSL": true,
    "UserName": "[email protected]",
    "Password": "12345"
},

And the registration of the settings class in the Program.cs class:

builder.Services.Configure<EmailSettings>(builder.Configuration.GetSection("EmailSettings"));

After that, you can call the settings class with dependency injection like that :

public class HomeController : Controller
{
    private EmailSettings _emailSettings;
    
    public HomeController(IOptions<EmailSettings> emailSettings)
    {
        _emailSettings= emailSettings.Value; // Don't forget the .Value
    }
    
    public IActionResult Index()
    {
        // Get the configuration items like that
        string getConfig = _emailSettings.Host;
        return View();
    }
}