Skip to content

Prevent singletons with container-scoped dependencies #266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

julian99m
Copy link

... by passing singleton-information within the resolution context and checking it during resolution.

Conceptually, singletons should not use container-scoped dependencies.
I can not think of any use case where the previous behavior (initializing a singleton that uses one specific instance of a container-scoped dependency) would be useful. In fact, it could lead to hard-to-detect bugs by using unexpected instances.

As this could be a breaking change, it might be necessary to have the change only be activated by configuration. Please give me feedback in that regard :)

…leton-information within the resolution context and checking it during resolution.
@julian99m
Copy link
Author

@microsoft-github-policy-service agree company="freenet DLS GmbH"

@julian99m julian99m marked this pull request as ready for review April 15, 2025 11:16
@Xapphire13
Copy link
Collaborator

Is the bug/undefined behavior we're trying to prevent, the scenario where a child container instantiates a parent container's singleton, which now has a dependency scoped to the child container?

@julian99m
Copy link
Author

Is the bug/undefined behavior we're trying to prevent, the scenario where a child container instantiates a parent container's singleton, which now has a dependency scoped to the child container?

basically, yes. I'd say the issue is not limited to parent/child-containers, but generally to singletons using container-scoped dependencies. But the scenario you described is probably the most common one where this happens.

@julian99m
Copy link
Author

Wait, now you got me thinking... parent container instances using child container instances is not a subset of singletons using container-scoped dependencies. Instead, they are separate scenarios that can overlap (because singletons are registered in the global container).
Regarding the expected behavior, I am unsure if parent container instances using child container instances should also be prevented, or if there are valid use cases for that behavior. Anyhow, this scenario is not covered by my current changes.

@julian99m
Copy link
Author

Any opinions on this topic?

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

Successfully merging this pull request may close these issues.

2 participants