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"?
You can register the same type more than once with the
IServiceCollectionand theServiceProviderwill automatically resolve all of them to anIEnumerable<>.For instance, if you want users of your library to add custom
ICommandobjects they would simply do the following in their own library:The
ServiceProviderwill automatically add them to the list ofIEnumerable<ICommand>where requested (across library boundaries).