Skip to content

Instantly share code, notes, and snippets.

@chaosmonster
Created June 21, 2023 15:29
Show Gist options
  • Save chaosmonster/8083f58c958846c0c9f8456d72e11161 to your computer and use it in GitHub Desktop.
Save chaosmonster/8083f58c958846c0c9f8456d72e11161 to your computer and use it in GitHub Desktop.
minimal dependency injection example in JavaScript
// minimal working dependency injection
// the dependency injection works with a property based injection
const clazzMap = Symbol('clazzMap');
globalThis[clazzMap] = new Map(); // <clazz, instance>
const clazzes = Symbol('clazzes')
globalThis[clazzes] = [];
function register(clazz) {
globalThis[clazzes].push(clazz);
}
function inject(clazz) {
if (globalThis[clazzMap].has(clazz)) {
return globalThis[clazzMap].get(clazz);
}
if (globalThis[clazzes].includes(clazz)) {
const instance = new clazz();
globalThis[clazzMap].set(clazz, instance);
return instance;
}
throw new Error(`no class registered for class ${clazz.name}`);
}
// Example of usage with JavaScript classes
class A {
name = 'barA';
}
class B {
name = 'barB';
c = inject(C);
}
class C {
name = 'barC';
a = inject(A);
}
// order of registering does not matter
register(C);
register(A);
// first injection can only happen after all needed classes are registered
const a = inject(A);
// you can register new classes delayed as long as previous injects to not rely on it
register(B);
const b = inject(B);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment