Warm tip: This article is reproduced from serverfault.com, please click

.net core-C# 如何跨库边界在 IServiceCollection 中建立集合?

(.net core - C# How do you build up a collection in the IServiceCollection across library boundaries?)

发布于 2021-10-20 17:37:58

List<ICommand>我通过构造函数注入一个通用列表。我的库的用户应该能够添加他们自己的ICommand. 所有ICommand实现在编译时都是已知的。目前,我添加ServiceCollection了以下内容(我意识到还有其他方法可以做到这一点):

ServiceCollection.AddSingleton<List<ICommand>>>(new List<ICommand>()
{
   new Command1(),
   new Command2(),
   new etc....
});

这适用于添加ICommand当前库中定义的实现。但是,我希望其他人使用我的库并添加他们自己的ICommand. ICommand他们如何从这个List<ICommand>库之外添加自己的?

我正在使用这个特定的例子List<T>来理解一个更普遍的问题:“你如何使用”建立一个对象库边界ServiceCollection

Questioner
Matt Newcomb
Viewed
0
Matt Newcomb 2021-10-23 01:13:47

你可以使用 多次注册相同的类型,IServiceCollection并且ServiceProvider自动将它们全部解析为IEnumerable<>.

例如,如果你希望库的用户添加自定义ICommand对象,他们只需在自己的库中执行以下操作:

serviceCollection.AddSingleton<ICommand, CustomCommand1>();
serviceCollection.AddSingleton<ICommand, CustomCommand2>();
serviceCollection.AddSingleton<ICommand, CustomCommand3>();

ServiceProvider自动将它们添加到IEnumerable<ICommand>请求的列表中(跨库边界)。