A feature that a lot of IoC container libraries support but that was missing in the default DI container provided by Microsoft is the support for Keyed or Named Services.
This feature allows you to register the same type multiple times using different names, allowing you to resolve a specific instance based on the circumstances. Although there is some controversy if supporting this feature is a good idea or not, it certainly can be handy.
To support this feature a new interface IKeyedServiceProvider got introduced in .NET 8 providing 2 new methods on our ServiceProvider instance:
- object? GetKeyedService(Type serviceType, object? serviceKey);
- object GetRequiredKeyedService(Type serviceType, object? serviceKey);
To use it, we need to register our service using one of the new extension methods:
Resolving the service can be done either through the FromKeyedServices
attribute:
or by injecting the IKeyedServiceProvider
interface and calling the GetRequiredKeyedService
method: