@codespeaks/tinydi
Version:
A simple and intuitive DI container, designed for simplicity, making dependency management seamless and easy to use.
46 lines (45 loc) • 2.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createContainer = void 0;
class TinyDI {
constructor() {
this.container = new Map();
this.injectWrapper = (registration) => ({
inject: (...depRefs) => this.inject(registration, ...depRefs),
getSelf: () => this.get(registration.classRef),
});
}
add(classRef, factory) {
const registration = Object.assign({ lifecycle: factory ? 'transient' : 'singleton', classRef }, (factory ? { factory } : {}));
this.container.set(classRef, registration);
return this.injectWrapper(registration);
}
get(classRef) {
var _a;
const registration = this.container.get(classRef);
if (!registration) {
throw new Error(`You should first add the class before retrieving it`);
}
if ((registration === null || registration === void 0 ? void 0 : registration.lifecycle) === 'singleton' && registration.instance) {
return registration.instance;
}
if ((registration === null || registration === void 0 ? void 0 : registration.lifecycle) === 'singleton' && !registration.instance) {
const instance = new registration.classRef();
registration.instance = instance;
this.container.set(classRef, registration);
return instance;
}
return (_a = registration === null || registration === void 0 ? void 0 : registration.factory) === null || _a === void 0 ? void 0 : _a.call(registration);
}
inject(registration, ...depRefs) {
if (!registration) {
throw new Error(`You should first add the class before injecting it`);
}
const depInstances = depRefs.map((depRef) => this.get(depRef));
registration.instance = new registration.classRef(...depInstances);
this.container.set(registration.classRef, registration);
return registration.instance;
}
}
const createContainer = () => new TinyDI();
exports.createContainer = createContainer;