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

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

Closed
@kimbell

Description

@kimbell

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions