Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNet Core DI: TryAdd vs Add usage

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?

like image 586
smg Avatar asked Jan 19 '17 13:01

smg


Video Answer


1 Answers

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.

like image 72
Joe Audette Avatar answered Dec 09 '22 23:12

Joe Audette