BanksySan
BanksySan

Reputation: 28530

Multiple config files with same values

I have multiple config files that I need to read (all JSON). The file contents are structurally identical. e.g.

alice.json

{ "Name": "Alice" }

bob.json

{ "Name": "Bob" }

How should I load them all into IConfiguration without them overwriting each other? Can I tell the framework to put them into sections matching theit filenames?

Upvotes: 0

Views: 757

Answers (2)

Matthew Abbott
Matthew Abbott

Reputation: 61599

I don't feel this is a best fit for IConfiguration. Configuration is specially designed to layer various configuration sources, where keys overwrite other keys - this is by design.

You may want to jump out of configuration, and handle these using a JSON serialiser directly, and merge the result objects.

public class Person
{
  public string Name { get; set; }
}

public class People
{
  public string[] Names { get; set; }
}

public static People LoadPeople(string[] personJson)
  => new People
  {
    Names = JsonConvert.Deserialize<Person>(personJson).Select(p => p.Name).ToArray()
  };

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239380

What you want is not possible. Configuration is loaded in serially, in the order the configuration providers are registered, and each successive source overrides any previous source. The only way to achieve something like what you want is to actually set it up that way in your JSON, i.e.:

alice.json

{
  "alice.json": {
    "Name": "Alice"
  }
}

bob.json

{
  "bob.json": {
    "Name": "Bob"
  }
}

Upvotes: 2

Related Questions