Sources has comment that TryAdd
version do not adds service if it is already registered in IServiceCollection
. But docs doesn't mention this method.
When it should be used?
Typically if you have a library with dependencies you would create an extension method of IServiceCollection that the consumer of you library would call from startup to wire up the default dependencies.
.TryAdd is useful inside your extension method when only one implementation of an interface should be used. Then if someone wants to override a default implementation they can register it before calling your extension method and since their implementation is registered first the TryAdd won't add anything.
If .Add is used in your extension method, one can still override the default implementation by registering their implementation after the call to your extension method. But in this case there are still multiple implementations registered so one could take a dependency on IEnumerable of IFoo and get all the implementations that have been registered. But if they take a dependency on IFoo they get just the default one ie the last one added.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With