This package has been deprecated

Author message:

use @simple-ui/di

simple-ui_di

1.0.1 • Public • Published

Dependency Injection

Coverage Status Build Status Dependency Status npm version

A dependency injection library using TypeScript decorators.

Install

Install with npm.

npm install --save simple-ui_di

Install with bower.

bower install --save simple-ui_di

Setup

The library uses Decorators to dress classes. To use this library you have to enable experimentalDecorators in your tsconfig.json file.

{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

The library uses ES6 exports for all decorators and the main DI object. To import the full library into a file you can destructure the export object.

import { di, provide, inject, ready } from 'simple-ui_di';

The four object you are injecting are:

Object Purpose
di The main DI container
provide A decorator to register a provided object
inject A decorator to inject a provided object
ready A decorator to register a function to call after the constructor when all objects have been injected

Injecting An Object

While a DI system handles creation of all object, there has to be one object created with starts the process. Here is a contrived example which demonstrates the full capabilities of the library.

import { di, provide, inject, ready } from 'simple-ui_di';
 
@provide()
class ServiceA {
  constructor() {
    console.log(`ServiceA exists`);
  }
 
  @ready()
  onReady_forA() {
    console.log(`ServiceA is ready`);
  }
}
 
@provide()
class ServiceB {
  
  @inject()
  public serviceA: ServiceA;
 
  constructor() {
    console.log(`ServiceB exists`);
  }
 
  @ready()
  onReady_forB() {
    console.log(`ServiceB is ready`);
  }
}
 
const serviceB: ServiceB = di.injectProvider('ServiceB');

Output of this code is, which describes the order of operations, the services are created and then ready functions are called.

ServiceB exists
ServiceA exists
ServiceA is ready
ServiceB is ready

The variable of an @inject() must be the name of the service with the first letter lowercase.

DI Containers

The system supports mulitple DI containers for namespacing. There is currently no mechanism to combine two DI namespaces. All providers have been register to the 'global' namespace so far.

import { di, provide, inject, ready } from 'simple-ui_di';
 
@provide('my-namespace')
class A {
 
}
 
@provide('my-namespace')
class B {
  @inject('my-namespace')
  public a: A;
}

To inject an object with di you can use the second parameter to reference a namespace.

di.injectProvider('InNamespace2', 'namespace-2');

Future Enhancements

A list of future enhancements.

  • Connect two or more DI container namespaces

Readme

Keywords

Package Sidebar

Install

npm i simple-ui_di

Weekly Downloads

1

Version

1.0.1

License

MIT

Last publish

Collaborators

  • mwjaworski