简体   繁体   中英

What's the best method to access configuration in .NET 6?

The second answer of this question: ASP.NET Core 6 how to access Configuration during startup mentioned that we can access configuration in this way:

A nice feature worth considering it to create a class that represents your settings and then bind the configuration to an instance of that class type. For example, let's assume you create a new class called MyAppSettings with the same structure as your appSettings.json, you can do the following:

var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;

I am confused about it and I want to know how to do that and what are the benefits of this.

What's more, the best method to access configuration in .NET 6?


Explain my question in more detail. The appSetting.json file in my project has only one layer like this:

{
 "name": "jack",
 ...1000+,
 "age": "100"
}

So I cannot configure it using builder.congiguration.GetSection():

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

How to configure it at once without changing the structure of appSettings.json?

thank you again~

You can refer to this simple demo to learn about how to

create a class that represents your settings and then bind the configuration to an instance of that class type

The values in appsetting.json :

"UserCred": {
      "Username":"Jack",
      "Password":"123"
},

Create a model class:

public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Configure in your programs.cs :

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

In the controller, use DI to inject it, then you can get the model with value:

public class HomeController : Controller
{
    private readonly IOptions<User> _configuration;

    public HomeController(IOptions<User> configuration)
    {
        _configuration = configuration;
    }

    //.......
}

在此处输入图像描述

What's the benefit?

For me, if there are many data ​​in appsetting.json , Creating a class to map them only needs to map once, You don't need to get them one by one, which makes coding more convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM