Any issues when injecting the same dependency across different modules within the same app?

97 Views Asked by At

I'm currently attempting to modularise an angular app by splitting it into features with each feature being a module that has it's own dependencies.

Example structure:

angular.module('myApp', ['myApp.whatever1', 'myApp.whatever2']);

angular.module('myApp.whatever1', ['ui.router']);

angular.module('myApp.whatever2', ['ui.router']);

As you can see the modules 'whatever1' and 'whatever2' both require the same dependency ('ui.router' in this case).

A) When injecting a dependency that has already been injected elsewhere in the app, are there any issues concerning injection conflicts / performance? In terms of conflicts I've read that Angular's dependency injector will simply override any duplicate dependency with the last one injected. In terms of performance I'm completely in the dark.

B) I thought that having the 'ui.router' dependency for each 'whateverX' module would be preferable to declaring the 'ui.router' dependency on just the 'myApp' module due to dependency/code clarity and possibly ease of testing. Is this correct or am I modularising up the wrong tree?

Many thanks

1

There are 1 best solutions below

1
AJ Funk On BEST ANSWER

A) When injecting a dependency that has already been injected elsewhere in the app, are there any issues concerning injection conflicts / performance? In terms of conflicts I've read that Angular's dependency injector will simply override any duplicate dependency with the last one injected. In terms of performance I'm completely in the dark.

No, this is what dependency injection is for. It allows you to reuse dependencies wherever you need them. There is obviously going to be some overhead when injecting a dependency, but it is very small and I wouldn't worry about it at all.

B) I thought that having the 'ui.router' dependency for each 'whateverX' module would be preferable to declaring the 'ui.router' dependency on just the 'myApp' module due to dependency/code clarity and possibly ease of testing.

Do you need ui.router in every module? The idea of DI is that you inject the dependencies where you need them, but don't inject them if you don't. If you need ui.router in each module then yes, inject it. However, I don't see how adding it to all of your modules makes your code more clear or testable.

You either need that dependency in that module or you don't. That should be what determines if it is included.