扩展 EcsDocument编辑

在使用 IDictionary<string, object> Metadata 属性不足够的情况下,或者您想要索引的 ECS 兼容文档结构有更清晰的定义,可以对 EcsDocument 对象进行子类化并提供您自己的属性定义。

通过 TryRead/ReceiveProperty/WriteAdditionalProperties,您可以挂接到 EcsDocumentJsonConverter 中并读取/写入其他属性。

/// <summary>
/// An extended ECS document with an additional property
/// </summary>
[JsonConverter(typeof(EcsDocumentJsonConverterFactory))]
public class MyEcsDocument : EcsDocument
{
	[JsonPropertyName("my_root_property"), DataMember(Name = "my_root_property")]
	public MyCustomType MyRootProperty { get; set; }

	protected override bool TryRead(string propertyName, out Type type)
	{
		type = propertyName switch
		{
			"my_root_property" => typeof(MyCustomType),
			_ => null
		};
		return type != null;
	}

	protected override bool ReceiveProperty(string propertyName, object value) =>
		propertyName switch
		{
			"my_root_property" => null != (MyRootProperty = value as MyCustomType),
			_ => false
		};

	protected override void WriteAdditionalProperties(Action<string, object> write) => write("my_root_property", MyCustomType);
}

Elastic.CommonSchema.BenchmarkDotNetExporter 项目在 Domain 源码目录 中采用这种方法,其中 BenchmarkDocument 是 EcsDocument 的子类。