将配置作为子类对象读入基类对象的集合



我有.Net核心应用程序,它使用appsettigs.json文件来保存配置。我需要将一个配置节加载到集合中,而无需对它们进行迭代。我知道我可以使用Bind((方法将集合绑定到相同类型的集合中。但在这里,我试图在集合中获取子类类型的对象,而不是基类类型的对象。

"Sections": [
{
"Name": "Section 1",
"Type":"type1"
},
{
"Name": "Section 2",
"Type":"type2"
},
{
"Name": "Section 3",
"Type":"type1"
},
{
"Name": "Section 4",
"Type":"type1"
},
{
"Name": "Section 5",
"Type":"type2"
}]

我正在使用下面的代码来读取配置文件。

var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var Configuration = configBuilder.Build();

我知道我可以使用Configuration.Bind((

类别为

Public abstract class BaseSection:ISection
{
public string Name;
..
}

Public class Type1:BaseSection
{
public string Name;
..
}
Public class Type2:BaseSection
{
public string Name;
..
}

我需要将appsettings.json文件中的配置读取到List,这样配置文件中具有"type=type1"的for条目将在集合type1 obejct中具有类型,并且"type=type2"将在集合type2 obejct中将具有类型。

所以我从上面的配置条目中收集的应该有

[
Object Of Type1
Object Of Type2
Object Of Type1
Object Of Type1
Object Of Type2
]

我不想一次读取数据,然后键入cast。

请分享观点和意见。提前谢谢。

您可以使用带绑定的中间列表,但您必须做一些工作来实例化正确的类型。你可以这样做:

namespace CoreApp1
{
public class ConfigSectionItem: BaseSection
{
public string Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = configBuilder.Build();
var confList = new List<ConfigSectionItem>();
configuration.GetSection("Sections").Bind(confList);
foreach (var confItem in confList)
{
var typeToBuild = Type.GetType($"CoreApp1.{confItem.Type}"); // Remember to do some checks with typeToBuild (not null, ...)
var newInstance = (BaseSection)Activator.CreateInstance(typeToBuild);
newInstance.Name = confItem.Name; // Use automapper or reflexion
// do what you want here with your newInstance
Console.WriteLine(newInstance.GetType().FullName + " " + newInstance.Name);
}
}
}
public abstract class BaseSection
{
public string Name;
}
public class Type1 : BaseSection
{
}
public class Type2 : BaseSection
{
}
}

请确保使用Microsoft.Extension.Configuration.Binder请注意在.json中区分大小写,或者做一些大写的工作:

"Type": "Type1"
"Type": "Type2"

最新更新