ConfigurationModel和强类型配置

本文关键字:配置 强类型 ConfigurationModel | 更新日期: 2023-09-27 18:16:27

我喜欢新的ASP。. NET 5配置库,所以我想在控制台应用程序中使用它。它可以很好地用于松散类型的配置。但是我不知道如何使用强类型版本。

如何从这里工作?我有两个类

class Vehicle
{
    public string Description { get; set; }
    public int Mpg { get; set; }
    public Paint Paint { get; set; }
}
class Paint
{
    public string MajorColor { get; set; }
    public string MinorColor { get; set; }
}

和配置文件:

<config>
  <vehicle>
    <description>Truck</description>
    <mpg>20</mpg>
    <paint>
      <majorcolor>white</majorcolor>
      <minorcolor>black</minorcolor>
    </paint>
  </vehicle>
</config>

我如何使用它?

var config = new Configuration();
config.AddXmlFile("../../StrongeConfig.xml");
?

第一个不工作的解:

var path = Path.GetFullPath("..''..''config.json");
var build = new ConfigurationBuilder()
   .AddXmlFile(path);
var configuration = build.Build();
configuration.Bind(v);
Console.WriteLine(v.ToString());

给了我一辆空车

ConfigurationModel和强类型配置

示例:https://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs#L400-L401

构建一个配置构建器,并使用它绑定到你的强类型对象


更新:

class MyConfig
{
    public Vehicle Vehicle { get; set; }
}
class Vehicle
{
    public string Description { get; set; }
    public int Mpg { get; set; }
    public Paint Paint { get; set; }
}
class Paint
{
    public string MajorColor { get; set; }
    public string MinorColor { get; set; }
}
public class Program
{
    public void Main(string[] args)
    {
        var config = new ConfigurationBuilder();
        config.AddXmlFile(@"x.xml");
        var configuration = config.Build();
        //Approach 1 (top level object)
        var topConfig = new MyConfig();
        configuration.Bind(topConfig);
        Console.WriteLine(topConfig.Vehicle.Paint.MajorColor);
        //Approach 2 (scoped)
        var vehicleSection = configuration.GetSection("Vehicle");
        var vehicle = new Vehicle();
        vehicleSection.Bind(vehicle);
        Console.WriteLine(vehicle.Paint.MajorColor);
    }
}