YamlDotNet and anchor references

Yaml is a convenient format for config storing . There are bindings in most of the popular programming languages, including .NET. The latter is well served by the library called YamlDotNet.

Yaml has a nice feature calls anchors which allows you to reuse portions of config. It works like this:

  1. foo: &anchor
  2.   K1: "One"
  3.   K2: "Two"
  5. bar:
  6.   <<: *anchor
  7.   K2: "I Changed"
  8.   K3: "Three"

Essentially bar will start with everything foo has and then either add or override these values as needed. YamlDotNet supports this feature. Unfortunately, it's documentation isn't very clear on the subject. In particular, it doesn't mention that the feature will not work with the vanilla deserializer. Luckily, all you have to do is to use the bundled MergingParser like this:

  1.                 using (var file = File.OpenText(configFile))
  2.                 {
  3.                     var deserializer = new DeserializerBuilder()
  4.                         .WithNamingConvention(new CamelCaseNamingConvention())
  5.                         .Build();
  6.                     configs = deserializer.Deserialize<IDictionary<string, Config>>(new MergingParser(new Parser(file)));
  7.                 }

That's it!


Add new comment