Are dependencies shared?

2019-06-23 18:11发布

Let's say I have 3 modules:

angular.module('A', [])

angular.module('B', ['A'])

angular.module('C', ['B', 'A'])

In terms of dependency injection, will B and C share the same instance of module A, or will separate instances be injected into each of them?

1条回答
疯言疯语
2楼-- · 2019-06-23 19:04

To summarize your question, answer would be only one instance.

In fact it is this way. Angular app resolves dependencies via injector. Only one injector is created per app. Technically you can have only one ng-app, but you can have multiple apps by using manual bootstrapping, in that case there will be an injector created for each app and those 2 apps will not share any dependencies.

In general case where there is only rootElement bootstrapped as an angular app. It resolves the modules starting the module that has been bootstrapped (starting from the bottom of the dependency chain). Any services/controllers/filters etc registered under that module or any dependent modules under that dependency chain will be bundled together in the injector cache(instantiated lazily when injected) just once. For example say you have a service myService registered under module A. No matter how many places you list A as dependency ultimately only one instance of its constructor will be available, and service being a singleton everyone gets the same singleton instance.

Official Doc:

Modules can list other modules as their dependencies. Depending on a module implies that the required module needs to be loaded before the requiring module is loaded. In other words the configuration blocks of the required modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

查看更多
登录 后发表回答