Dead simple dependency injection for Typescript.
Install the module as a dependency in your project:
npm i super-injector --save
Add the Injectable decorator and resolve a class with dependencies:
Super Injector will new up your class and all of its dependencies
import { Injectable, Injector } from 'super-injector';
@Injectable()
class SomeClass {
public message: string = 'Hello World!';
}
@Injectable()
class AnotherClass {
constructor(private someClass: SomeClass) {
}
get message(): string {
return this.someClass.message;
}
}
const anotherClassInstance: AnotherClass = Injector.resolve(AnotherClass);
console.log(anotherClassInstance.message);
// logs "Hello World" to the console
Set metadata on classes before instantiation:
import { Injectable, Injector } from 'super-injector';
@Injectable()
class TestClass {}
// set a property at the test class level
Injector.set(TestClass, { someProp: 'Hello World' });
console.log(Injector.get(TestClass, 'someProp'));
// logs "Hello World" to the console
You can set metadata at design time and retrieve it at run time:
import { Metadata, Injector } from 'super-injector';
class SomeClass {
@Metadata({
someProp: 'Hello World',
anotherProp: 'Hi World'
})
someMethod(): void {
// ..
}
}
const someClassInstance: AnotherClass = Injector.resolve(someClassInstance);
console.log(Injector.get(someClassInstance, 'someProp', null, 'someMethod'));
// logs Hello World to the console
console.log(Injector.getAll(someClassInstance, 'someMethod'));
// logs { "someProp": "Hello World", "anotherProp": "Hi World" } to the console
We use SemVer for versioning. For the versions available, see the tags on this repository.
This project is licensed under the MIT License - see the LICENSE.md file for details