1.0.4 • Published 6 years ago

addiction v1.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

Addiction

A TypeScript dependency injection solution.

Get Started

You can start using Addiction in two simple steps

Installation

Install via npm

npm i addiction

or via yarn

yarn add addiction

Make sure that your tsconfig.json has the following properties set to true.

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Usage

Addiction workflow is very simple, take a look at the example below

import { TransientService, ServiceProvider } from "addiction";

@TransientService()
export class Foo {
  public getFoo(): string {
    return "foo";
  }
}

@TransientService()
export class Bar {
  private readonly _foo: Foo;

  constructor(foo: Foo) {
    this._foo = foo;
  }

  public getFoo(): string {
    return this._foo.getFoo();
  }
}

const bar = ServiceProvider.resolve(Bar);

console.log(bar.getFoo()); // => "foo"

What's included?

Addiction has two main class decorators TransientService and SingletonService, the main ServiceProvider, and the direct useService method.

TransientService

Can be used to mark a service/class as a Transitive dependency.

SingletonService

Can be used to mark a service/class as a Singleton dependency.

ServiceProvider

The entry point of Addiction workflow, used mainly to resolve service's dependencies.

Consumer

Consumer class is the class that has dependencies injected to it but can't be used itself as a dependency. (this is the edge of the flat earth :smiley:)

Inject

Inject is a constructor parameter decorator used with the Consumer class decorator to mark a specific parameter as a auto injected dependency/parameter.

for instance

import { Inject, Consumer, TransientService, Injected } from "addiction";

@TransientService()
export class Foo {
  public getFoo(): string {
    return "foo";
  }
}

@Consumer()
export class Bar {
  private readonly _foo: Foo;

  /**
   * use the Injected helper method to be able to call the class with the new keyword.
   */
  constructor(@Inject(Foo) foo: Foo = Injected()) {
    this._foo = foo;
  }

  public getFoo(): string {
    return this._foo.getFoo();
  }
}
// ServiceProvider.resolve is omitted, or actually the Consumer
// decorator will call it for you.
console.log(new Bar().getFoo()); // => "foo"

Injected

As described in the example above, it's just a work around to be able to call the class using the new keyword.

this method is just returning undefined as any.

Note from the author

Addiction library is very simple, and there’re many features that not yet implemented, I’ve built this library mainly to use it in a React.Js app, and I’ll update it and implement new features in my free time.

Contributing

Any contribution is more than welcome :heart: just make sure to test your code :nerd_face:.

1.0.4

6 years ago

1.0.3

6 years ago

1.0.0

6 years ago