英文:
Create configuration class with interitance from base class without duplication in config.json
问题
以下是您要翻译的内容:
"I have a few similar classes with similar configurations in it.
So, I want to create a base Class with common configuration, after that inherit it in child config class and in the end initialize it in logic class:
public class OptionsBase
{
public string ConnectionKey { get; set; }
}
public class OptionsChild: OptionsBase
{
public string ChildName{ get; set; }
}
My json file:
"OptionsBase": {
"ConnectionKey": "basekey"
},
"OptionsChild": {
"ChildName": "child1"
}
Expecting to use it like this:
public class Child1
{
private readonly OptionsChild _options;
public Child1(IOptions<OptionsChild> options)
{
_options = options.Value;
}
public void Example()
{
var valueFromParent = _options.ConnectionKey;
}
}
How can I do it without duplication in json file and without using additional common class with common options?
It is web app, config initialization executed like this:
service.Configure<OptionsChild>(config.GetSection("OptionsChild"));
Thank you!
EDIT: I found the solution and added an answer. Please, let me know if the solution is OK."
希望这对您有所帮助。如果您有任何其他问题,请随时提出。
英文:
I have a few similar classes with similar configurations in it.
So, I want to create a base Class with common configuration, after that inherit it in child config class and in the end initialize it in logic class:
public class OptionsBase
{
public string ConnectionKey { get; set; }
}
public class OptionsChild: OptionsBase
{
public string ChildName{ get; set; }
}
My json file:
"OptionsBase": {
"ConnectionKey": "basekey"
},
"OptionsChild": {
"ChildName" "child1"
}
Expecting to use it like this:
public class Child1
{
private readonly OptionsChild _options;
public Child1(IOptions<OptionsChild> options)
{
_options = options.Value;
}
public void Example()
{
var valueFromParent = _options.ConnectionKey;
}
}
How can I do it without duplication in json file and without using additional common class with common options?
It is web app, config initialization executed like this:
service.Configure<OptionsChild>(config.GetSection("OptionsChild"));
Thank you!
EDIT: I found the solution and added an answer. Please, let me know if the solution is OK.
答案1
得分: 1
我找到了一个答案,在这里 描述了,正是我想要的内容。
这有点绕,需要为每个配置类配置两次,但这样我可以在子选项类中使用基本选项,而无需在JSON文件中重复配置。
请告诉我这个解决方案是否可以。
英文:
I have found an answer, here it is described, exactly what I wanted to receive.
It is a bit workaround, need to configure each configuration class twice, but this way I can use base options without duplicating options in child options class and also I don't need to duplicate configuration in JSON file
Please, let me know if the solution is OK.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论