Husain
Husain

Reputation: 845

ConfigurationModel and Strongly Typed Configuration

I liked the new ASP.NET 5 Configuration library, so I want to use it in a console application. It works fine for loosely-typed configuration. but I don't know how to use the strongly-typed version.

How to work from here? I have two classes

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; }
}

And the configuration file:

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

How do I use that?

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

First non-working solution:

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

which gave me an empty vehicle.

Upvotes: 3

Views: 737

Answers (1)

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

Here's an example: https://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs#L400-L401

Build a configuration builder and the use it to bind to your strong type object


Updated:

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);
    }
}

Upvotes: 2

Related Questions