Injectors
Bunshi is a dependency injection tool — it creates instances of objects, classes and libraries for you on demand. The injector keeps track of all of those instances and stores them efficiently internally.
Most of the time you won’t need to interact with the injector directly. It quietly works behind the scenes in the framework integrations. However, there are some cases when you may need to create your own injector to bind molecule interfaces to implementations.
API
The core API for injectors is createInjector.
import { molecule, moleculeInterface, createInjector } from "bunshi";
const NumberMolecule = moleculeInterface<number>();
const RandomNumberMolecule = molecule<number>(() => Math.random());
const injector = createInjector({
bindings: [[NumberMolecule, RandomNumberMolecule]],
});
Injectors can inherit from parent injectors, creating a hierarchy where child injectors can access parent bindings while adding their own:
const parentInjector = createInjector({
bindings: [[LoggerInterface, ConsoleLoggerMolecule]]
});
const childInjector = createInjector({
parent: parentInjector,
bindings: [[DatabaseInterface, SqliteMolecule]]
});
// Child can access both DatabaseInterface (local) and LoggerInterface (from parent)