Skip to content
This repository has been archived by the owner on Nov 2, 2018. It is now read-only.

Question: Multiple calls to AddSingleton<TInterface,TImplementation> #544

Closed
kimbell opened this issue Jul 5, 2017 · 2 comments
Closed

Comments

@kimbell
Copy link

kimbell commented Jul 5, 2017

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.

@davidfowl
Copy link
Member

Its about the consumption. The current contract for the IServiceCollection is as you describe. If you add multiple services and the consumer asks for a list, it'll manifest all of them. If you ask for a single one, then you'll get the last one.

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.

At the moment it's a requirement for all of the adapters (it's part of the specification tests) so if you use an adapter for Microsoft.Extensions.DependendencyInjection that passes the tests behaves like this.

There's a much longer discussion here about the requirements in general #433.

@kimbell
Copy link
Author

kimbell commented Jul 8, 2017

Thanks, learn something every day :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants