C#服务集合将类型添加为对象,而不是其实际类型



我的代码有点问题。

基本上,我试图将通过反序列化JSON创建的类动态添加到ServiceCollection中,这样我就可以从任何需要它们的类中获得它们。到目前为止,我得到了以下代码:

Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(AbstractConfiguration)) && !t.IsAbstract).ToList().ForEach(x => {
if (!File.Exists(x.Name + ".json")) {
object Configuration = Activator.CreateInstance(x);
File.WriteAllText(x.Name + ".json", JsonSerializer.Serialize(Configuration, new JsonSerializerOptions() { WriteIndented = true }));
ServiceCollection.AddSingleton(Configuration);
} else {
string json = File.ReadAllText(x.Name + ".json");
object Configuration = JsonSerializer.Deserialize(json, x, new JsonSerializerOptions() { WriteIndented = true });
ServiceCollection.AddSingleton(Configuration);
}
});

然而,我们将JSON加载到一个类中(有效(,然后将其添加到我们的集合(有效(;当添加到我们的集合中时,类型是一个对象,所以当我尝试通过Services.GetServices(typeof(BotConfiguration)).ToList().Count);调用它时,它返回0。什么东西?

如果我们试着运行Services.GetServices(typeof(object)).ToList().ForEach(x => Console.WriteLine(x.ToString()));,我们实际上可以看到这个实例化实际上属于对象类型,尽管当我们运行x.ToString((时,它表明它是BotConfiguration的一个实例(在我的情况下输出Dexter.Core.Configuration.BotConfiguration(。

我们如何让ServiceCollection将其添加为实际的类而不是对象?它清楚地知道它是什么类型的。。。?

您的代码正在调用方法的泛型版本(AddSingleton<TService>(IServiceCollection, TService)(,其中泛型类型参数在编译时解析为object,请尝试调用一个接受Type参数(请参阅所有重载(,如下所示:

ServiceCollection.AddSingleton(x);

UPD

存在接受类型和对象实例的过载(AddSingleton(IServiceCollection, Type, Object)(:

ServiceCollection.AddSingleton(x, Configuration);

最新更新