1.0.2 • Published 4 years ago

lightinject v1.0.2

Weekly downloads
21
License
ISC
Repository
github
Last release
4 years ago

Injector

This is a super light injector which could be used with Typescript or Javascript.

Examples:

Simple usage :

const { injectAs, default: injector } = require('lightinject');


/**
 * Class injection. 
 * By default it will instantiate a class service before injecting it.
 */

class HelloSrv {
  hello() {
    console.log('hello');
  }
}

injector.set(HelloSrv, 'helloSrv');

/**
 * Function injection.
 * By default it will invoke a function service before injecting it.
 */

function elapsedMillisecondsSrv() {
  const date = new Date();
  return () => {
    const now = new Date();
    return now.getTime() - date.getTime();
  };
}

injector.set(elapsedMillisecondsSrv, 'elapsedMillisecondsSrv');

/**
 * Value injection.
 * By default it will simply inject a constant service.
 */

const hoursInDay = 24;

injector.set(hoursInDay, 'hoursInDay');


function test(
  service = injector.get('helloSrv'), 
  elapsed = injector.get('elapsedMillisecondsSrv'), 
  constant = injector.get('hoursInDay')
) {
  console.log(elapsed(), 'ms');
  service.hello();
  console.log(constant);
  console.log(elapsed(), 'ms');
}

test();

Typescript

import injector, { Injector, injectAs } from 'lightinject';

class HelloSrv {
  hello() {
    console.log('hello');
  }
}

injector.set(HelloSrv, 'helloSrv');

function test(srv = injector.get<HelloSrv>('helloSrv')) {
  srv.hello();
}

test();

Control the way services are injected

It is possible to define how services will be injected as follows :

const { injectAs, default: injector } = require('lightinject');

function currentMillisecondsDate() {
  return new Date().getTime();
}

injector.set(currentMillisecondsDate, 'currentMillisecondsDate', { as: injectAs.value });

function test2(currentMs = injector.get('currentMillisecondsDate')) {
  console.log(currentMs());
}

test2();

Control instance unicity

It is possible to recreate instances before each injection (by default the same instance is injected at each injection).

class HelloSrv2 {
  constructor() {
    this.date = new Date();
  }

  hello() {
    console.log('created at', this.date.toISOString());
  }
}

injector.set(HelloSrv2, 'helloSrv2', { unique: false });

function test3(srv = injector.get('helloSrv2')) {
  srv.hello();
}

function test4(srv = injector.get('helloSrv2')) {
  srv.hello();
}

test3();
setTimeout(() => test4(), 1000);
// will print different dates
1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago