How to use GetServices(IServiceProvider, Type)

Bevan Thomas 60 Reputation points
2025-10-02T20:33:39.66+00:00
Developer technologies | .NET | .NET Runtime
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jack Dang (WICLOUD CORPORATION) 2,685 Reputation points Microsoft External Staff
    2025-10-03T02:46:33.3+00:00

    Hi @Bevan Thomas ,

    Thanks for reaching out.

    GetServices(IServiceProvider, Type) works by internally asking the container for IEnumerable<serviceType>. This means it will return all the implementations that were registered under that service type. For example, if you registered multiple classes against the same interface, GetServices will give you all of them.

    However, it’s important to note that the built-in Microsoft dependency injection container does not support keyed or named registrations out of the box. GetServices won’t let you filter or select by key — it just gives you all instances.

    If you need keyed or named services, you’ll want to look at:

    • The newer keyed service APIs in IKeyedServiceProvider, which were added in recent .NET versions.
    • Or, if you’re using a third-party DI container, rely on its keyed/named resolution methods instead.

    Summary:

    • GetServices(IServiceProvider, Type) → gets all instances of the given type.
    • It does not handle keyed/named services by itself.
    • For keyed services, use GetKeyedService / GetKeyedServices or the equivalent feature in your chosen container.

    Hope this helps! If my answer was useful, please consider marking it as accepted so others with the same question can find it more easily.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.