This package has been deprecated

Author message:

Totemish is no longer maintained

@totemish/injector
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Injector

Core Build Status codecov semantic-release downloads version license

Totemish Injector brings a simple approach to dependency injection. Simply decorate what you mean to be injectable with @Injectable() and then @Inject() it where it needs to be in place. Your injectable will be available right in the constructor.

Totemish Injector is dependency free and does no automagic for you so that you don't end up having weird behaviour and fat metadata.

Installation

npm i --save @totemish/injector

Usage

There are two main ways you can set and get an injectable. The first one for both is to use decorators.

  • @Injectable(name?) allows you to mark code that you want to be injectable in other parts of your code. You can provide an optional name argument and it will override the default name of the injectable (by default, it is the class name). If you do so, you won't be able to refer to the injectable via its class reference and you will always have to pass the name you've specified.

  • @Inject(...names) allows injecting one or multiple injectables marked with @Injectable. You will be able to get them via the constructor of the class that has the @Inject decorator. If you have multiple injectables for a class, follow the same order you provide them to @Inject. This rule is quite easy to follow yet saves us from lots of extra code.

Example
import { Injectable, Inject, InjectableInterface } from '@totemish/injector';

@Injectable()
export class Mouth {
  public say(phrase: string): void {
    console.log(`${phrase}!`);
  }
}

/**
 * You can give specific names for services if you need to. Those names are generated even
 * if you don't provide them, they just use the class name, like with the Mouth class
 */
@Injectable('thoughtfulness')
export class Brain {
  public getCleverThought(): string {
    return 'Polymorphism is when Gammy bears go polygamy';
  }
}

@Inject('thoughtfulness', Mouth)
export class Human {
  public constructor(private brain: Brain, private mouth: Mouth) {}
  
  public saySomethingClever() {
    this.mouth.say(this.brain.getCleverThought());
  }
}

Links

Package Sidebar

Install

npm i @totemish/injector

Weekly Downloads

4

Version

1.0.0

License

MIT

Unpacked Size

81.6 kB

Total Files

55

Last publish

Collaborators