Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 732
explorer Avatar asked Nov 25 '25 12:11

explorer


1 Answers

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!

like image 119
explorer Avatar answered Nov 28 '25 01:11

explorer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!