Method for the. net core static class to get appsettings

  • 2021-11-13 07:10:49
  • OfStack

Injection acquisition

Injection access through IConfiguration direct access to the method in the official document, you can directly see here

For example: appsettings. json


{
  "Position": {
    "Title": " Editor ",
    "Name": "Joe Smith"
  },
  "MyKey": "My appsettings.json Value",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

You can take the value in the form of colon separation with injected IConfiguration, as follows


 var name = Configuration["Position:Name"];

Entity class acquisition

It is not convenient to obtain the values corresponding to multiple combinations individually. For example, Logging should be received directly with one class as follows:
First define a class corresponding to the json node


 public class Logging
  {
    public LogLevel LogLevel { get; set; }
  }
  public class LogLevel
  {
    public string Default { get; set; }
    public string Microsoft { get; set; }
    public string Lifetime { get; set; }
  }

Then ConfigureServices increases in Startup


services.Configure<Logging>(Configuration.GetSection("Logging"));

Inject directly into the place called


 private readonly Logging _config;
 public HomeController(IOptions<Logging> config)
 {
   _config = config.Value;
 }

Static class acquisition

If it is used in a static class, you can write this in the constructor in Startup


public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
      configuration.GetSection("Logging").Bind(MySettings.Setting);
    }

Bind the node directly to an instance using the Bind method of IConfigurationSection, noting that the example must be initialized.


public static class MySettings
  {
    public static Logging Setting { get; set; } = new Logging();
  }

With the properties of static classes, they can be used in static classes.


Related articles: