Skip to content
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

Support for priority based selection of injected types (Primary, Secondary) #1

Open
hjohn opened this issue May 12, 2022 · 0 comments

Comments

@hjohn
Copy link
Owner

hjohn commented May 12, 2022

When multiple types qualify for an injection site, and the site allows only one an AmbiguousDependencyException will be thrown. Some DI systems allow for annotations to make an automatic selection and resolve the ambiguity:

  • @Primary: favor this dependency over any others; assuming there is only one primary annotated dependency, than the ambiguity is resolved.
  • @Secondary: only use this dependency if no others are available; if all other dependencies except one are secondary, then the one that is not annotated as secondary is used and the ambiguity is resolved.

A priority based system would seem to be able to support these annotations without forcing specific annotations. @Primary could be priority 1, @Secondary priority -1 and any unannotated types would be priority 0. Extending the AnnotationStrategy with a method to return the priority of an AnnotatedElement should suffice to support this in the core code, while leaving the choice of annotations (and how many) up to the strategy.

Internally, the InjectableStore would need to changed to be aware of situations where multiple beans may match but ultimately don't cause ambiguity. Examples:

Should allow:

  • Registering a higher priority type of the same type as a lower priority type is not ambiguous
  • Registering a lower priority type of the same type as a higher priority type is not ambiguous

Should reject:

  • Removing the only highest priority type of the same type as multiple lower but equal priority types may cause an existing dependency to become ambiguous

As the consistency currently is verified with a simple counter, this may need to become a counter for each priority level or the counter must be recalculated when the highest priority type is removed.

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

No branches or pull requests

1 participant