feat(core): ContainerUtil添加两个工具函数:getContainerDictionary
和getContainerDictionaryMap
#216
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
添加这两个函数的意图
inversify内部似乎没有明面上提供任何可以遍历某个容器类内所有元素的方法,这导致很难去做一些全局的操作,每一个扩展的库都得实现一个Map、至少一个以上的装饰器来遍历所有被装饰器标记过的类,局限性很大。
但是我们可以避开TypeScript编译器,通过
container['_bindingDictionary']
拿到这个隐藏在Container
上的Dictionary;通过dictionary['_map']
拿到该Dictionary上的Map
(即实际上的inversify存放元素的容器)。添加了这两个工具函数,我们就可以拿到所有的类,对这些收集到的类做一些其他事情了:
一些顾虑
加上这两个函数有利也有弊。是否
真的
要把这两个函数加上去?访问
和修改
容器的学习成本大大降低,会不会导致一些混乱的事情发生:比如在A人在B处通过ContainerUtil
修改了容器,但是C人不知道,又在D处通过ContainerUtil
修改了容器;多人改来改去,导致代码混乱。关于这个问题,想了挺久,如果真的考虑把这两个函数加上去的话,那么我们必须在文档里注明code style:
除了开发库以外,正常情况下在生产项目中少去遍历容器和修改容器内的东西,否则可能会导致代码混乱,难已维护
等相关的code style提示。@ApiTags
等装饰器,那我通过Reflect.defineMetadata
定义了一些元数据,我甚至没法拿到这个元数据!唯一的解法是只能靠我自己维护一个Class Map。但是设想一下:很多库都有这样的需求怎么办?那岂不是每一个库都得自己维护一个Class Map!这既导致了内存的浪费,而且也极不方便,开发范式也不统一。
反正综上,既有好处也有坏处,请项目的creator三思而后合并。