Search code examples
c#.net-coredependency-injectionservice-providerservicecollection

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


Solution

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