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()));,我们实际上可以看到该实例实际上属于 object 类型,即使我们运行x.ToString()时,它也显示它是BotConfiguration的实例(在我的情况下,输出Dexter.Core.Configurations.BotConfiguration)。

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

解决方法

您的代码正在调用方法(AddSingleton<TService>(IServiceCollection,TService))的通用版本,并且在编译时将通用类型参数解析为object,请尝试调用一个接受的Type参数(请参阅全部{{3 }}):

ServiceCollection.AddSingleton(x);

UPD

有重载(AddSingleton(IServiceCollection,Type,Object))接受类型和对象实例:

ServiceCollection.AddSingleton(x,Configuration);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...