dependency-injection-es6
dependency-injection-es6 is a dependency injection library for Node.js and Javascript environments where ES6 is supported.
Dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.
Installation
$ npm install --save dependency-injection-es6
Requirements
dependency-injection-es6 requires a Javascript environment with ES6 classes and decorators. Babel is included as a dependency to make the library compatible with environments that do not support these features directly.
Getting Started
For resolving dependencies of classes you will need to use @inject decorator and container class to resolve instance
; {} @ config:SameClass;
Example
Service Classes
{}
; @singleton { console; }
EmailService is one of the implementations of MessageService. Notice that class is annotated with @singleton annotation. Since service objects will be created through injector classes, this annotation is provided to let them know that the service classes are singleton objects.
We have another service implementation to send facebook messages.
; { console; }
Consumer Class
;; @ service:MessageService; { console; }
Bindings
; //bind the service to implementation classcontainer; //or bind MessageService to Facebook Message implementation //container.bind(MessageService,FacebookService); //make a singleton with option {singleton:true}//container.bind(MessageService,MessageService,{singleton:true});
Resolve instance
var instance = container;instanceservice;
You can get injected class instance by calling getInstanceOf() method.
; { return /** .. **/} @ config:Config; @ service:Service; var service = container;console;
Inject with constructor.
;;; @ { thismyDependency1 = myDependency1; thismyDependency2 = myDependency2; }
Dependencies of a class are injected through the constructor.