2

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"?

Matt Newcomb
  • 101
  • 5
  • 3
    By exposing your `ICommand` and registering them one by one (both you and your consumers), not as a list as a singleton, and requesting an `IEnumerable` where you need all registered commands. – CodeCaster Oct 20 '21 at 17:40
  • @CodeCaster that works. I never found that in the documentation. Thanks. If you writeup an answer I will mark it as the accepted answer – Matt Newcomb Oct 20 '21 at 18:47
  • Nah I'm sure there are duplicates that explain it, couldn't find any that quickly. Feel free to self-answer with your solution. – CodeCaster Oct 21 '21 at 05:50

1 Answers1

3

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).

Matt Newcomb
  • 101
  • 5