UNPKG

18.8 kBMarkdownView Raw
1# InversifyJS
2
3[![Join the chat at https://discord.gg/jXcMagAPnm](https://img.shields.io/discord/816766547879657532?label=discord%20chat&logo=discord)](https://discord.gg/jXcMagAPnm)
4![Build Status](https://github.com/inversify/InversifyJS/actions/workflows/node.js.yml/badge.svg)
5
6[![Test Coverage](https://codeclimate.com/github/inversify/InversifyJS/badges/coverage.svg)](https://codeclimate.com/github/inversify/InversifyJS/coverage)
7[![npm version](https://badge.fury.io/js/inversify.svg)](http://badge.fury.io/js/inversify)
8[![Dependencies](https://david-dm.org/inversify/InversifyJS.svg)](https://david-dm.org/inversify/InversifyJS#info=dependencies)
9[![img](https://david-dm.org/inversify/InversifyJS/dev-status.svg)](https://david-dm.org/inversify/InversifyJS/#info=devDependencies)
10[![img](https://david-dm.org/inversify/InversifyJS/peer-status.svg)](https://david-dm.org/inversify/InversifyJS/#info=peerDependenciess)
11[![Known Vulnerabilities](https://snyk.io/test/github/inversify/InversifyJS/badge.svg)](https://snyk.io/test/github/inversify/InversifyJS)
12[![Twitter Follow](https://img.shields.io/twitter/follow/InversifyJS.svg?style=flat&maxAge=86400)](https://twitter.com/inversifyjs)
13
14[![NPM](https://nodei.co/npm/inversify.png?downloads=true&downloadRank=true)](https://nodei.co/npm/inversify/)
15[![NPM](https://nodei.co/npm-dl/inversify.png?months=9&height=3)](https://nodei.co/npm/inversify/)
16
17![](https://raw.githubusercontent.com/inversify/inversify.github.io/master/img/cover.jpg)
18
19A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
20
21## About
22InversifyJS is a lightweight inversion of control (IoC) container for TypeScript and JavaScript apps.
23An IoC container uses a class constructor to identify and inject its dependencies.
24InversifyJS has a friendly API and encourages the usage of the best OOP and IoC practices.
25
26## Motivation
27JavaScript now supports object oriented (OO) programming with class based inheritance. These features are great but the truth is that they are also
28[dangerous](https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4).
29
30We need a good OO design ([SOLID](https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)), [Composite Reuse](https://en.wikipedia.org/wiki/Composition_over_inheritance), etc.) to protect ourselves from these threats. The problem is that OO design is difficult and that is exactly why we created InversifyJS.
31
32InversifyJS is a tool that helps JavaScript developers write code with good OO design.
33
34## Philosophy
35InversifyJS has been developed with 4 main goals:
36
371. Allow JavaScript developers to write code that adheres to the SOLID principles.
38
392. Facilitate and encourage the adherence to the best OOP and IoC practices.
40
413. Add as little runtime overhead as possible.
42
434. Provide a [state of the art development experience](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md).
44
45## Testimonies
46
47**[Nate Kohari](https://twitter.com/nkohari)** - Author of [Ninject](https://github.com/ninject/Ninject)
48
49> *"Nice work! I've taken a couple shots at creating DI frameworks for JavaScript and TypeScript, but the lack of RTTI really hinders things.*
50> *The ES7 metadata gets us part of the way there (as you've discovered). Keep up the great work!"*
51
52**[Michel Weststrate](https://twitter.com/mweststrate)** - Author of [MobX](https://github.com/mobxjs/mobx)
53> *Dependency injection like InversifyJS works nicely*
54
55## Some companies using InversifyJS
56
57[<img src="https://avatars0.githubusercontent.com/u/6154722?s=200&v=4" width="100" />](https://opensource.microsoft.com/)[<img src="https://avatars2.githubusercontent.com/u/69631?s=200&v=4" width="100" />](https://code.facebook.com/projects/1021334114569758/nuclide/)[<img src="https://avatars0.githubusercontent.com/u/2232217?s=200&v=4" width="100" />](https://aws.github.io/aws-amplify/)[<img src="https://avatars0.githubusercontent.com/u/1520648?s=200&v=4" width="100" />](https://www.plainconcepts.com/)[<img src="https://avatars3.githubusercontent.com/u/6962987?s=200&v=4" width="100" />](https://api.slack.com/)[<img src="https://pbs.twimg.com/profile_images/827249559046909954/SyaBPcH8_400x400.jpg" width="100" />](http://acia.aon.com/index.php/home/) [<img src="https://avatars3.githubusercontent.com/u/114767?s=200&v=4" width="100" />](https://www.lonelyplanet.com/) [<img src="https://avatars0.githubusercontent.com/u/25283328?s=200&v=4" width="100" />](https://jincor.com/) [<img src="https://avatars1.githubusercontent.com/u/1957282?s=200&v=4" width="100" />](https://www.web-computing.de/) [<img src="https://avatars1.githubusercontent.com/u/17648048?s=200&v=4" width="100" />](https://dcos.io/) [<img src="https://avatars0.githubusercontent.com/u/16970371?s=200&v=4" width="100" />](https://typefox.io/) [<img src="https://avatars0.githubusercontent.com/u/18010308?s=200&v=4" width="100" />](https://code4.ro/) [<img src="https://user-images.githubusercontent.com/10656223/33888109-fae0852e-df43-11e7-97f6-9db543da0bde.png" width="100">](http://www.baidu.com/) [<img src="https://avatars2.githubusercontent.com/u/8085382?s=200&v=4" width="100" />](https://www.imdada.cn/) [<img src="https://avatars2.githubusercontent.com/u/17041151?s=200&v=4" width="100" />](https://www.ato.gov.au/) [<img src="https://avatars1.githubusercontent.com/u/14963540?s=200&v=4" width="100" />](https://www.kaneoh.com/) [<img src="https://avatars0.githubusercontent.com/u/26021686?s=200&v=4" width="100" />](https://particl.io/) [<img src="https://avatars2.githubusercontent.com/u/24523195?s=200&v=4" width="100" />](https://slackmap.com/) [<img src="https://avatars3.githubusercontent.com/u/16556899?s=200&v=4" width="100" />](https://www.go1.com/) [<img src="https://avatars3.githubusercontent.com/u/23475730?s=200&v=4" width="100" />](http://www.stellwagengroup.com/stellwagen-technology/) [<img src="https://avatars1.githubusercontent.com/u/15262567?s=200&v=4" width="100" />](https://www.edrlab.org/) [<img src="https://avatars1.githubusercontent.com/u/10072104?s=200&v=4" width="100" />](https://www.goodgamestudios.com/) [<img src="https://avatars2.githubusercontent.com/u/13613760?s=200&v=4" width="100" />](https://freshfox.at/) [<img src="https://avatars1.githubusercontent.com/u/864482?s=200&v=4" width="100" />](https://schubergphilis.com/)
58
59## Installation
60
61You can get the latest release and the type definitions using npm:
62
63```
64$ npm install inversify reflect-metadata --save
65```
66
67The InversifyJS type definitions are included in the inversify npm package.
68
69> :warning: **Important!** InversifyJS requires TypeScript >= 2.0 and the `experimentalDecorators`, `emitDecoratorMetadata`, `types` and `lib`
70compilation options in your `tsconfig.json` file.
71
72```js
73{
74 "compilerOptions": {
75 "target": "es5",
76 "lib": ["es6"],
77 "types": ["reflect-metadata"],
78 "module": "commonjs",
79 "moduleResolution": "node",
80 "experimentalDecorators": true,
81 "emitDecoratorMetadata": true
82 }
83}
84```
85
86InversifyJS requires a modern JavaScript engine with support for:
87
88- [Reflect metadata](https://rbuckton.github.io/reflect-metadata/)
89- [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
90- [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) (Only required if using [provider injection](https://github.com/inversify/InversifyJS/blob/master/wiki/provider_injection.md))
91- [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) (Only required if using [activation handlers](https://github.com/inversify/InversifyJS/blob/master/wiki/activation_handler.md))
92
93If your environment doesn't support one of these you will need to import a shim or polyfill.
94
95> :warning: **The `reflect-metadata` polyfill should be imported only once in your entire application** because the Reflect object is meant to be a global singleton. More details about this can be found [here](https://github.com/inversify/InversifyJS/issues/262#issuecomment-227593844).
96
97Check out the [Environment support and polyfills](https://github.com/inversify/InversifyJS/blob/master/wiki/environment.md)
98page in the wiki and the [Basic example](https://github.com/inversify/inversify-basic-example) to learn more.
99
100## The Basics
101Let’s take a look at the basic usage and APIs of InversifyJS with TypeScript:
102
103### Step 1: Declare your interfaces and types
104
105Our goal is to write code that adheres to the [dependency inversion principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle).
106This means that we should "depend upon Abstractions and do not depend upon concretions".
107Let's start by declaring some interfaces (abstractions).
108
109```ts
110// file interfaces.ts
111
112export interface Warrior {
113 fight(): string;
114 sneak(): string;
115}
116
117export interface Weapon {
118 hit(): string;
119}
120
121export interface ThrowableWeapon {
122 throw(): string;
123}
124```
125
126InversifyJS needs to use the type as identifiers at runtime. We use symbols as identifiers but you can also use classes and or string literals.
127
128```ts
129// file types.ts
130
131const TYPES = {
132 Warrior: Symbol.for("Warrior"),
133 Weapon: Symbol.for("Weapon"),
134 ThrowableWeapon: Symbol.for("ThrowableWeapon")
135};
136
137export { TYPES };
138
139```
140
141> **Note**: It is recommended to use Symbols but InversifyJS also support the usage of Classes and string literals (please refer to the features section to learn more).
142
143### Step 2: Declare dependencies using the `@injectable` & `@inject` decorators
144Let's continue by declaring some classes (concretions). The classes are implementations of the interfaces that we just declared. All the classes must be annotated with the `@injectable` decorator.
145
146When a class has a dependency on an interface we also need to use the `@inject` decorator to define an identifier for the interface that will be available at runtime. In this case we will use the Symbols `Symbol.for("Weapon")` and `Symbol.for("ThrowableWeapon")` as runtime identifiers.
147
148```ts
149// file entities.ts
150
151import { injectable, inject } from "inversify";
152import "reflect-metadata";
153import { Weapon, ThrowableWeapon, Warrior } from "./interfaces";
154import { TYPES } from "./types";
155
156@injectable()
157class Katana implements Weapon {
158 public hit() {
159 return "cut!";
160 }
161}
162
163@injectable()
164class Shuriken implements ThrowableWeapon {
165 public throw() {
166 return "hit!";
167 }
168}
169
170@injectable()
171class Ninja implements Warrior {
172
173 private _katana: Weapon;
174 private _shuriken: ThrowableWeapon;
175
176 public constructor(
177 @inject(TYPES.Weapon) katana: Weapon,
178 @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
179 ) {
180 this._katana = katana;
181 this._shuriken = shuriken;
182 }
183
184 public fight() { return this._katana.hit(); }
185 public sneak() { return this._shuriken.throw(); }
186
187}
188
189export { Ninja, Katana, Shuriken };
190```
191
192If you prefer it you can use property injection instead of constructor injection so you don't have to declare the class constructor:
193
194```ts
195@injectable()
196class Ninja implements Warrior {
197 @inject(TYPES.Weapon) private _katana: Weapon;
198 @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon;
199 public fight() { return this._katana.hit(); }
200 public sneak() { return this._shuriken.throw(); }
201}
202```
203
204### Step 3: Create and configure a Container
205We recommend to do this in a file named `inversify.config.ts`. This is the only place in which there is some coupling.
206In the rest of your application your classes should be free of references to other classes.
207```ts
208// file inversify.config.ts
209
210import { Container } from "inversify";
211import { TYPES } from "./types";
212import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
213import { Ninja, Katana, Shuriken } from "./entities";
214
215const myContainer = new Container();
216myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
217myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
218myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);
219
220export { myContainer };
221```
222
223### Step 4: Resolve dependencies
224You can use the method `get<T>` from the `Container` class to resolve a dependency.
225Remember that you should do this only in your [composition root](http://blog.ploeh.dk/2011/07/28/CompositionRoot/)
226to avoid the [service locator anti-pattern](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/).
227
228```ts
229import { myContainer } from "./inversify.config";
230import { TYPES } from "./types";
231import { Warrior } from "./interfaces";
232
233const ninja = myContainer.get<Warrior>(TYPES.Warrior);
234
235expect(ninja.fight()).eql("cut!"); // true
236expect(ninja.sneak()).eql("hit!"); // true
237```
238
239As we can see the `Katana` and `Shuriken` were successfully resolved and injected into `Ninja`.
240
241InversifyJS supports ES5 and ES6 and can work without TypeScript.
242Head to the [**JavaScript example**](https://github.com/inversify/InversifyJS/blob/master/wiki/basic_js_example.md) to learn more!
243
244## The InversifyJS Features and API
245Let's take a look to the InversifyJS features!
246
247- [Support for classes](https://github.com/inversify/InversifyJS/blob/master/wiki/classes_as_id.md)
248- [Support for Symbols](https://github.com/inversify/InversifyJS/blob/master/wiki/symbols_as_id.md)
249- [Container API](https://github.com/inversify/InversifyJS/blob/master/wiki/container_api.md)
250- [Declaring container modules](https://github.com/inversify/InversifyJS/blob/master/wiki/container_modules.md)
251- [Container snapshots](https://github.com/inversify/InversifyJS/blob/master/wiki/container_snapshots.md)
252- [Controlling the scope of the dependencies](https://github.com/inversify/InversifyJS/blob/master/wiki/scope.md)
253- [Declaring optional dependencies](https://github.com/inversify/InversifyJS/blob/master/wiki/optional_dependencies.md)
254- [Injecting a constant or dynamic value](https://github.com/inversify/InversifyJS/blob/master/wiki/value_injection.md)
255- [Injecting a class constructor](https://github.com/inversify/InversifyJS/blob/master/wiki/constructor_injection.md)
256- [Injecting a Factory](https://github.com/inversify/InversifyJS/blob/master/wiki/factory_injection.md)
257- [Auto factory](https://github.com/inversify/InversifyJS/blob/master/wiki/auto_factory.md)
258- [Auto named factory](https://github.com/inversify/InversifyJS/blob/master/wiki/auto_named_factory.md)
259- [Injecting a Provider (asynchronous Factory)](https://github.com/inversify/InversifyJS/blob/master/wiki/provider_injection.md)
260- [Activation handler](https://github.com/inversify/InversifyJS/blob/master/wiki/activation_handler.md)
261- [Deactivation handler](https://github.com/inversify/InversifyJS/blob/master/wiki/deactivation_handler.md)
262- [Post Construct decorator](https://github.com/inversify/InversifyJS/blob/master/wiki/post_construct.md)
263- [Middleware](https://github.com/inversify/InversifyJS/blob/master/wiki/middleware.md)
264- [Multi-injection](https://github.com/inversify/InversifyJS/blob/master/wiki/multi_injection.md)
265- [Tagged bindings](https://github.com/inversify/InversifyJS/blob/master/wiki/tagged_bindings.md)
266- [Create your own tag decorators](https://github.com/inversify/InversifyJS/blob/master/wiki/custom_tag_decorators.md)
267- [Named bindings](https://github.com/inversify/InversifyJS/blob/master/wiki/named_bindings.md)
268- [Default target](https://github.com/inversify/InversifyJS/blob/master/wiki/default_targets.md)
269- [Support for hierarchical DI systems](https://github.com/inversify/InversifyJS/blob/master/wiki/hierarchical_di.md)
270- [Contextual bindings & @targetName](https://github.com/inversify/InversifyJS/blob/master/wiki/contextual_bindings.md)
271- [Property injection](https://github.com/inversify/InversifyJS/blob/master/wiki/property_injection.md)
272- [Circular dependencies](https://github.com/inversify/InversifyJS/blob/master/wiki/circular_dependencies.md)
273- [Inheritance](https://github.com/inversify/InversifyJS/blob/master/wiki/inheritance.md)
274
275Please refer to the [wiki](https://github.com/inversify/InversifyJS/blob/master/wiki/readme.md) for additional details.
276
277## Ecosystem
278In order to provide a state of the art development experience we are also working on:
279
280- [Middleware extensions](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#extensions).
281- [Development tools](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#development-tools).
282- [Examples](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#examples).
283
284Please refer to the [ecosystem wiki page](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md) to learn more.
285
286## Support
287If you are experience any kind of issues we will be happy to help. You can report an issue using the [issues page](https://github.com/inversify/InversifyJS/issues) or the [chat](https://gitter.im/inversify/InversifyJS). You can also ask questions at [Stack overflow](http://stackoverflow.com/tags/inversifyjs) using the `inversifyjs` tag.
288
289If you want to share your thoughts with the development team or join us you will be able to do so using the [official the mailing list](https://groups.google.com/forum/#!forum/inversifyjs). You can check out the
290[wiki](https://github.com/inversify/InversifyJS/blob/master/wiki/readme.md) to learn more about InversifyJS internals.
291
292## Acknowledgements
293
294Thanks a lot to all the [contributors](https://github.com/inversify/InversifyJS/graphs/contributors), all the developers out there using InversifyJS and all those that help us to spread the word by sharing content about InversifyJS online. Without your feedback and support this project would not be possible.
295
296## License
297
298License under the MIT License (MIT)
299
300Copyright © 2015-2017 [Remo H. Jansen](http://www.remojansen.com)
301
302Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
303
304The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
305
306THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
307
308IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.