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

C# How do you build up a collection in the IServiceCollection across library boundaries?

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

I inject a generic list List<ICommand> through a constructor. Users of my library should be able to add their own implementations of ICommand. All of the ICommand implementations are known at compile time. Currently, I add to the ServiceCollection something like the following (i realize there are other ways to do this as well) :

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

This works well for adding ICommand implementations defined in the current library. However, I want others to use my library and add their own implementations of ICommand. How do they add their own ICommand to this List<ICommand> from outside of this library?

I am using this specific example with List<T> to understand a more general problem: "how do you build up an object ACROSS library boundaries using ServiceCollection"?

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

You can register the same type more than once with the IServiceCollection and the ServiceProvider will automatically resolve all of them to an IEnumerable<>.

For instance, if you want users of your library to add custom ICommand objects they would simply do the following in their own library:

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

The ServiceProvider will automatically add them to the list of IEnumerable<ICommand> where requested (across library boundaries).