pureinject
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

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

Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY

Dependents (0)

Package Sidebar

Install

npm i pureinject

Weekly Downloads

13

Version

1.0.1

License

ISC

Unpacked Size

199 kB

Total Files

12

Last publish

Collaborators

  • benhurott