使用 .NET 创建可定制的配置
我正在尝试创建一些类似于以下代码片段的类型化配置...
<logging application="Global Application Name">
<defaultLogger name="default" genericOption="XXX" specificOptionYYY="yyy" />
<defaultLogger name="notAsDefault" genericOption="AAA" specificOptionYYY="bbb" />
<anotherDefaultLogger name="anotherDefault" genericOption="ZZZ" specificOptionWWW="www" />
</logging>
根部将是一个 LoggerSettings 类,其中包含 application
属性和 LoggingConfigurationElement
的集合s。
LoggingConfigurationElement 将包含 genericOption
属性。 然后将创建两个包含 specicOptionYYY
和 specicOptionWWW
的特定子类。
然后,我将如何在运行时根据元素的名称来匹配和实例化配置元素的正确子类?
I'm trying to create some typed configuration similar to the following snippet...
<logging application="Global Application Name">
<defaultLogger name="default" genericOption="XXX" specificOptionYYY="yyy" />
<defaultLogger name="notAsDefault" genericOption="AAA" specificOptionYYY="bbb" />
<anotherDefaultLogger name="anotherDefault" genericOption="ZZZ" specificOptionWWW="www" />
</logging>
At the root would be a LoggerSettings class that would contain the application
property and a collection of LoggingConfigurationElement
s.
The LoggingConfigurationElement would contain the genericOption
property.
There would then be two specific sub-classes that would be created containing the specificOptionYYY
and specificOptionWWW
.
How would I then go about matching and instantiating the correct sub-class of configuration element at run time based on the element's name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
诀窍是重写 OnDeserializeUnrecognizedElement 方法并动态创建所需的配置元素,然后手动反序列化它。
在此示例中,我使用反射和配置的组合预先构建了有效元素名称列表(是的,更多配置!),因此我可以预先知道所提供的元素是否有效。
The trick was to override the
OnDeserializeUnrecognizedElement
method and dynamically create the configuration element required, and deserialise it manually.In this example, I've pre-built the list of valid element names using a combination of reflection and configuration (yes, more configuration!) so I know up-front if the supplied element is a valid one.