In this post, we will be talking about the two types of relationships, namely, direct dependency relationship and enumeration. In terms of a component A and service B, these relationships can be stated as the following:

  • Direct Dependency – A needs B
  • Enumeration – A needs all the kinds of B


Direct Dependency (B)

It’s quite common to have a direct dependency relationship –  component A needs service B. In this case, the code for A would look like the following:


In order to make the above code work, all we need is to register the component and the service with your container. And then resolve as:


Enumeration (IEnumerable<B>, IList<B>, ICollection<B>)

When we inject a dependency of enumeration type, the DI container returns all the implementations of the same service. This is useful in cases like error loggers, where an event (an application error for instance) occurs and there are more than one logger registered to log the event.



Let’s say we have a service dependency interface as IAuditLogger defined as:


Further, the consumer of this service ErrorHandler, uses all the implementations of IAuditLogger to log any errors:


In order to make the above code work, all we need is to register all the implementations of IAuditLogger with the container. As a result, when we resolve the consumer, all the matching dependencies will be resolved as an enumerable.


It’s equally important to note that the container will return an empty list if no matching items are registered in the container. Therefore, in the above example, if we don’t register any implementation of IAuditLogger then we will get an empty list.


Igor · July 12, 2018 at 9:59 am

Where is ErrorHandler registration?

    Gaurav Gahlot · July 16, 2018 at 12:00 pm

    Hi Igor!

    Thanks for highlighting this. The registration for ErrorHandler was missing. Have corrected the code.
    Thank again! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.