1.0.1 • Published 5 years ago

pureinject v1.0.1

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

pureinject

A light, pure javascript, dependency free injection "framework" for javascript projects.

travis-master

logo

Setup

Just add to your dependencies using NPM or Yarn:

npm install pureinject

or

yarn add pureinject

How to use

const { createInjector } = require('pureinject');

class MyHttpService {
  // ...
}

class MyService {
  constructor(injector) {
    this._httpService = injector.resolve('MyHttpService');
  }
}

const injector = createInjector();

injector.register('MyHttpService', injector => {
  return new MyHttpService();
});

injector.register('MyService', injector => {
  return MyService(injector);
});

With Typescript

import { createInjector, PureInjector } from 'pureinject'

class MyHttpService {
  // ...
}

class MyService {

  private _httpService: MyHttpService

  constructor(injector: PureInjector) {
    this._httpService = injector.resolve<MyHttpService>('MyHttpService');
  }
}

const injector: PureInjector = createInjector()

injector.register('MyHttpService', (injector: PureInjector) => {
  return new MyHttpService();
})

injector.register('MyService', (injector: PureInjector) => {
  return MyService(injector);
});

How it works

It's simple: each time you call injector.resolve, it will run the the registered function and will retrieve the new instance of the service.

You can return what you want inside a registered module.

If you want to resolve a string value, you can!

const { createInjector } = require('pureinject');

class HttpService {
  constructor(injector) {
    this._apiUrl = injector.resolve('API_URL');
  }
}

const injector = createInjector();

injector.register('API_URL', injector => {
  return 'https://api.site.com';
});

injector.register('HttpService', injector => {
  return new HttpService(injector);
});

About

Thanks to