I am new at JavaScript. I wonder how dependency injection is being implemented in JavaScript? I searched the internet but couldn\'t find anything.
I am new at JavaScript. I wonder how dependency injection is being implemented in JavaScript? I searched the internet but couldn't find anything.
To be completely honest after working with JavaScript (mainly on the server side) and the whole ecosystem for a few years, I get the feeling that dependency injection (not to mention containers) hasn't really made it into a regular JS programmer's toolbox. That's probably the reason why there's not much information about it out there (it's getting better though).
As opposed to a language such as Java, you cannot rely on static types in JavaScript. This fact alone rules out the traditional way of declaring dependencies via interfaces. You can of course add types to JS (see Flow) but these get elided before the code gets executed. The same applies for TypeScript but I believe there's a way to preserve the types as non enforced metadata. Further, JavaScript doesn't support annotations (although there's a proposal for it).
People have been getting around the limitations in various ways. Some containers parse the function/class definition (as in they call .toString()
on the passed function/class and parse the resulting string) and look for dependencies based on the names, some require functions/classes to provide a property/static method to get the list of dependencies.
I've been working myself on a container called Ashley, which simply asks for the dependencies as part of the binding process. No further inspection required.
container.instance('Client', Client, ['DependencyA', 'DependencyB']);
container.instance('DependencyA', DependencyA, ['DependencyC']);
container.instance('DependencyB', DependencyB, ['DependencyC']);
container.instance('DependencyC', DependencyC, [], {
scope: 'Prototype', // Defaults to Singleton
initialize: true,
deinitialize: true
});
const client = await container.resolve('Client');
More examples on GitHub.