如何动态选择在依赖注入中使用的具体类

问题描述 投票:0回答:0

我通常会为我的

DI
写这样的东西:

            var serviceProvider = new ServiceCollection()
                .AddSingleton<ISomething, Something>()
                .AddSingleton<IOutputMaker, XMLOutputMaker>()
                .AddSingleton<IConfiguration>(Program.configuration)
                .BuildServiceProvider();

但是现在假设我从

config file
中读取了我应该生成的
type
输出。请注意,上面我有这一行:
 .AddSingleton<IOutputMaker, XMLOutputMaker>()
但我想更灵活一点,例如,如果配置文件显示
XML
那么,如果配置文件显示
XLSX
那么也许是这样的:
 .AddSingleton<IOutputMaker, ExcelOutputMaker>()

我怎样才能做到更灵活?

我不知道怎么办。也许我可以多次调用

BuildServiceProvider

c# dependency-injection factory-pattern strategy-pattern
© www.soinside.com 2019 - 2024. All rights reserved.