Question: Multiple calls to AddSingleton<TInterface,TImplementation> #544
Description
This question is inspired by some exploring with IHostedService
.
My understanding has been that the last call to AddSingleton()
replaces previously registered information.
Lets say the framework calls AddSingleton<IMemoryCache,MemoryCache>()
based on an AddXYZ() method.
I want my own implementation, so if I add AddSingleton<IMemoryCache,MyMemoryCache>()
after the framework, I get my implementation.
When playing with IHostedService, I discovered that I could add multiple services
AddSingleton<IHostedService, MyHostedService1>()
AddSingleton<IHostedService, MyHostedService2>()
Both services get activated, indicating that the DI system keeps track of all the registered implementations.
How does the DI system know what implementation to use if I have an object that requires a single IHostedService
? The HostedServiceExecutor
being used by the framework takes an IEnumerable<IHostedService>
.
Can we then deduce that if a single reference is needed, it takes the last one registered.
If it requests an IEnumerable
, we get everything?
If we take this one step further, and decide to use a different DI implementation. Is this type of behavior 'standard' in the other popular implementations? If one chooses the wrong DI system, it could have a negative effect on hosted services.