0.0.8 • Published 1 year ago

autoinjection v0.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

autoinjection

Automatic Dependency Injection for TypeScript.

Installation

Install autoject by npm.

npm install autoinjection

If you want to use autoinjection with interface, install ttypescript too.

npm install --save-dev ttypescript

Import 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.

ttsc

Usage

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() // foo

with 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() // foo

inject 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
0.0.8

1 year ago

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago