0.0.8 • Published 3 years ago
autoinjection v0.0.8
autoinjection
Automatic Dependency Injection for TypeScript.
Installation
Install autoject by npm.
npm install autoinjectionIf you want to use autoinjection with interface, install ttypescript too.
npm install --save-dev ttypescriptImport reflect-metadata package.
import 'refect-metadata'Set experimentalDecorators and emitDecoratorMetadata options to true in your tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}To use autoinjection with interface, add plugins option also.
{
"plugins": [
{
"transform": "autoinjection/lib/transform",
}
]
}And use the following command to compile.
ttscUsage
with class
import { Service, Inject } from 'autoinjection'
@Service()
class Foo {
print() {
console.log('foo')
}
}
@Service()
class Bar {
constructor(@Inject() private foo?: Foo) { }
print() {
this.foo?.print()
}
}
new Bar().print() // foowith interface
import { Service, Inject } from 'autoinjection'
interface IFoo { }
@Service()
class Foo implements IFoo {
print() {
console.log('foo')
}
}
@Service()
class Bar {
constructor(@Inject() private foo?: IFoo) { }
print() {
this.foo?.print()
}
}
new Bar().print() // fooinject dependency as singleton
import { Service, Inject } from 'autoinjection'
@Service({ singleton: true })
class Foo {
value = 0
print() {
console.log(this.value)
value++
}
}
@Service()
class Bar {
constructor(@Inject() private foo?: Foo) { }
print() {
this.foo?.print()
}
}
new Bar().print() // 0
new Bar().print() // 1