Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 778
Matt Newcomb Avatar asked Sep 20 '25 07:09

Matt Newcomb


1 Answers

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

like image 166
Matt Newcomb Avatar answered Sep 22 '25 22:09

Matt Newcomb