【问题标题】:ConfigurationModel and Strongly Typed ConfigurationConfigurationModel 和强类型配置
【发布时间】:2016-01-03 12:34:29
【问题描述】:

我喜欢新的 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());

这给了我一辆空车。

【问题讨论】:

  • 通常的新方法是使用 OptionsModel 命名空间在启动时将类的实例从配置连接到服务。有各种可能的配置源 xml、json、用户机密、环境变量,但它们通常做同样的事情,并且必须连接到可以注入的类。 shazwazza.com/post/using-aspnet5-optionsmodelstackoverflow.com/questions/32599573/…
  • @JoeAudette 我不确定在这种情况下如何使用它。页面中给出的代码适用于 ASP.NET MVC。

标签: c# asp.net-core


【解决方案1】:

这是一个例子: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);
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 2017-04-17
    • 2019-03-16
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多