1.1.3 • Published 2 years ago

attr-di v1.1.3

Weekly downloads
6
License
ISC
Repository
github
Last release
2 years ago

Attr-DI

Attribute based dependency injection library for TypeScript applications

Installation

Install using npm

npm install attr-di --save

Configuration

You first need to configure your project tsconfig.json file so that attr-di can work properly. You need to enable decorators and emit metadata as well

"experimentalDecorators": true,
"emitDecoratorMetadata": true

Usage

Select a class and before adding a decorator you need to select an injection type. Currently this library supports the following Lifetime injection types*

  1. Transient a new instance will be created.
  2. Singleton only a single copy will be created on first time it's requested (lazy loading) then this instance will be used throughout the application lifetime.

After selecting a type, delcaring a decorator is pretty easy

import { Injectable, InjectionTypes } from "attr-di";

@Injectable(InjectionTypes.Singleton)  // <-- Decorator declaration
export class Service1 {
    ...
}

Injection Patterns

The library can inject an instance using one of 2 patterns

 Constructor Injection

  This is the most famous type of injection basically all you need to do is to define a variable inside the constructor, just make sure that all created variables are for types that have an @Injectable() decorator, otherwise the library won't be able to create an instance

export class Component{
    constructor(private service : Service1){}
    ...
}

 Variable Injection

  This below example creates an instance manually when needed.

import { injectorInstance } from 'attr-di';

const component = injectorInstance.getInstance<Component>(Component);
import { injectorInstance } from 'attr-di';

const component = injectorInstance.getInstanceWithParameter<Component, Model>(Component);

In first example, you pass the requested instance type as the function parameter, and the required return type as the generic parameter.

As for the second example, you can pass an extra generic paramter which can be passed to generic instances like Component<T>.

1.1.3

2 years ago

1.1.1

3 years ago

1.1.2

3 years ago

1.1.0

3 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago