clazzify
v1.1.0
Published
Small dependency-injection and lazy-loading container for Node.js
Downloads
191
Maintainers
Readme
Clazzify
Small dependency-injection container and lazy loader for Node.js classes
High-level: Clazzify provides a tiny injector that registers class constructors by name, resolves them lazily and supports circular dependencies by creating lazy getters for declared properties.
Basic example
const Clazzify = require('./clazzify');
const injector = new Clazzify();
class A { constructor(b){ this.b = b } }
class B { constructor(){ } }
injector.register(A, { b: B });
injector.register(B);
const a = injector.resolve('A');
console.log(a.b); // instance of B (lazy-loaded via getter)Instance names
You can optionally register default instance name(s) for a class and then depend on those names directly:
const injector = new Clazzify();
class MyClass { constructor(){ this.id = 1 } }
class Consumer { constructor(){ /* getters will be defined */ } }
// Register a singleton with one or more instance names
injector.register(MyClass, null, ['myObject', 'primary']);
// Declare dependencies using instance names
injector.register(Consumer, ['myObject', 'primary']);
const consumer = injector.resolve('Consumer');
console.log(consumer.myObject === consumer.primary); // trueThis keeps compatibility with object mappings:
class Repo {}
class Service {}
// Object mapping: { propertyName: ClassOrName }
injector.register(Service, { repo: Repo });API
register(clazz, deps = null, instanceNames = null): Registers a class in the container, its dependencies, and default instance name(s).
- Parameters:
- clazz: constructor function (required).
- deps: object whose keys are instance names and values are classes or classes names
{ propName: ClassOrName }, array of instance names['instanceName', 'anotherInstanceName'], ornull/undefinedfor no dependencies (optional). - instanceNames: string or array of strings with default instance name(s) (optional).
- Returns: void.
- Parameters:
resolve(provider): Resolves (and initializes on first use) the singleton for a registered provider, wiring lazy getters for its dependencies.
- Parameters:
- provider: constructor function or provider name (string).
- Returns: the singleton instance of the registered class.
- Parameters:
clear(): Removes all registered providers, singletons, and instance-name mappings.
- Parameters: none.
- Returns: void.
