DEV Community 👩‍💻👨‍💻

Discussion on: Dependency Injection in JavaScript 101

randy808 profile image

I'll start by saying that this is a great introduction to dependency injection for those who understand Javascript, but I do agree with those who say an IoC container isn't necessary. In my personal experience, it added unneeded complexity in files where implementations were instantiated and registered. It also threw off other Javascript developers as it's not exactly a widely used paradigm within the Javascript development scene. Below I'll briefly address some of the initial motivations behind the usage of an IoC container in Javascript, and attempt to make a case that shows it may not be helpful when building Javascript applications.

To address each point:

1.) "If you attempt break each component (wheel, piston, etc.) into its own file, you will have to ensure everything is included in the right order for it to work"

I'm not sure this is true in a system like Javascript where the convention is to import all dependencies at the top of each file.

2.)"The tight coupling means it's not possible to have a developer working on engines while another is working on pistons. "

Again, a module system can easily allow something akin to a mock to be passed in.

3.)"The components create their own dependencies so there is no way to effectively test them without dependencies."

At least on the server side there are testing frameworks like "jest" that allow you to change the default behavior of require statements to retrieve a mock instead of actual implementations.