inversify / InversifyJS

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
http://inversify.io/
MIT License
11.15k stars 713 forks source link

The Symbol's examples are misleading #877

Open midnight-wonderer opened 6 years ago

midnight-wonderer commented 6 years ago

Either the examples are misleading or I am misunderstanding.
As stated in:
https://github.com/inversify/InversifyJS/blob/e2cf550/wiki/symbols_as_id.md

In very large applications using strings as the identifiers of the types to be injected by the InversifyJS can lead to naming collisions.

In that case the Symbol should be used like:

Symbol("Ninja")

not

Symbol.for("Ninja")

This return false

Symbol("Ninja") === Symbol("Ninja")

but this return true

Symbol.for("Ninja") === Symbol.for("Ninja")

currently the for usage does not limited to just in the document.

The changes seem to be deliberate though:
https://github.com/inversify/InversifyJS/pull/708

dcherman commented 6 years ago

👍

A misunderstanding of how Symbols work doesn't mean that we should change examples to use something that has the potential for global collisions. Instead, we should encourage people to learn how Symbols work by linking to MDN documentation, examples, etc.

Enough people just straight copy and paste examples that they should be based on best practices with explanations about why it's being done in a particular way.

bodograumann commented 5 years ago

Yes, please fix this.

This was my first proper encounter of Symbols and it was quite confusing to say the least. I'm still not sure if there is any real difference between using "Ninja" vs. Symbol.for("Ninja").

To prevent naming conflicts you definitely have to use Symbol("Ninja"). The caveat of that solution is that you have to access the symbol definition from everywhere that you want to inject something, plus in your composition root.