In ASP.NET Core 8, we have the option to register services using a key. Typically, injecting IEnumerable<ICustom>
in a constructor will return all services that are registered of the ICustom
.
But, how can I resolve a dictionary of the service along with their keys? For example, IDictionary<string, ICustom>
so I can access both the service and its key?
There's nothing included OOTB to get a dictionary of keyed services, but you can add this behavior using the following extension method:
After adding this code to your project, you use it as follows:
This allows you to resolve keyed registrations as an
IDictionary<TKey, TService>
. For instance, take a look at this fully working console application example:When running, the application will produce the following output: