Search code examples
c#asp.net.net-coredependency-injection

What is the precise difference between TryAddEnumerable(ServiceDescriptor) and other TryAdd{lifetime} calls


Both services.TryAddEnumerable(ServiceDescriptor) and the other group of calls (TryAddSingleton, TryAddScoped, TryAddTransient) seem to do the same thing -- they first check for prior registration of a service in the Dependency injection container and then only register it if it has not already been registered.

Here is the relevant link for the docs: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection --- it doesn't really clarify the difference and I couldn't find much from google search.


Solution

  • Ok, I found the difference:

    TryAdd{lifetime}() ... for example TryAddSingleton() ... peeps into the DI container and looks for whether ANY implementation type (concrete class) has been registered for the given service type (the interface). If yes then it does not register the implementation type (given in the call) for the service type (given in the call). If no , then it does.

    TryAddEnumerable(ServiceDescriptor) on the other hand peeps into the DI container , looks for whether the SAME implementation type (concrete class) as the implementation type given in the call has already been registered for the given service type. If yes, then it does not register the implementation type (given in the call) for the service type (given in the call). If no, then it does. Thats why there is the Enumerable suffix in there. The suffix indicates that it CAN register more than one implementation types for the same service type!