C# пользовательский элемент конфигурации
Я разрабатываю инструмент, который требует расширенной настройки, расположенной в файле App/config (Web.config). Чтобы добиться этого, я использовал пользовательский раздел конфигурации.
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="webConfiguration" type="MyConfigurationType, MyAssembly" />
</configSections>
<webConfiguration>
<requests>
<request name="Request-One">
<!-- details here, but they don't matter -->
</request>
<request name="Request-Two" basedOn="Request-One">
<!-- details here, but they don't matter -->
</request>
</requests>
</webConfiguration>
</configuration>
RequestElement.cs
public class RequestElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("basedOn", IsRequired = false)]
public string BasedOn
{
get
{
return (string)this["basedOn"];
}
set
{
this["basedOn"] = value;
}
}
}
Как видите, это довольно просто. Он компилируется и работает без исключений. Все, что я хочу спросить, возможно ли создать свойство конфигурации типа RequestElement
и связать это с правильным? (как показано ниже)
RequestElement.cs
public class RequestElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("basedOn", IsRequired = false)]
public RequestElement BasedOn
{
get
{
return (RequestElement)this["basedOn"];
}
set
{
this["basedOn"] = value;
}
}
}
Как вы заметили, Name
является ключом, поэтому использование имени в App.config
файл приведет к тому, что после открытия ConfigurationManager
и получив соответствующий раздел, затем запрос и любой из запросов, я смогу получить доступ к реальному объекту, используя BasedOn
имущество.