19.3 kBMarkdownView Raw
1![](https://raw.githubusercontent.com/inversify/inversify.github.io/master/img/cover.jpg)
2
3<p align="center">
4 <a href="https://www.npmjs.com/package/inversify" target="__blank"><img src="https://img.shields.io/npm/v/inversify?color=0476bc&label=" alt="NPM version"></a>
5 <a href="https://www.npmjs.com/package/inversify" target="__blank"><img alt="NPM Downloads" src="https://img.shields.io/npm/dm/inversify?color=3890aa&label="></a>
6 <a href="https://github.com/inversify/InversifyJS#-the-inversifyjs-features-and-api" target="__blank"><img src="https://img.shields.io/static/v1?label=&message=docs&color=1e8a7a" alt="Docs"></a>
7 <a href="https://codecov.io/gh/inversify/InversifyJS" target="__blank"><img alt="Codecov" src="https://codecov.io/gh/inversify/InversifyJS/branch/master/graph/badge.svg?token=KfAKzuGs01"></a>
8 <br>
9 <br>
10 <a href="https://github.com/inversify/InversifyJS" target="__blank"><img alt="GitHub stars" src="https://img.shields.io/github/stars/inversify/InversifyJS?style=social"></a>
11 <!--<a href="https://twitter.com/inversifyjs" target="__blank"><img alt="Twitter" src="https://img.shields.io/twitter/follow/InversifyJS.svg?maxAge=86400&style=social"></a>-->
12 <a href="https://discord.gg/jXcMagAPnm" target="__blank"><img alt="Discord Server" src="https://img.shields.io/discord/816766547879657532?style=social&logo=discord"></a>
13</p>
14
15# InversifyJS
16A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
17
18## About
19InversifyJS is a lightweight inversion of control (IoC) container for TypeScript and JavaScript apps.
20An IoC container uses a class constructor to identify and inject its dependencies.
21InversifyJS has a friendly API and encourages the usage of the best OOP and IoC practices.
22
23## Motivation
24JavaScript now supports object oriented (OO) programming with class based inheritance. These features are great but the truth is that they are also
25[dangerous](https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4).
26
27We 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.
28
29InversifyJS is a tool that helps JavaScript developers write code with good OO design.
30
31## Philosophy
32InversifyJS has been developed with 4 main goals:
33
341. Allow JavaScript developers to write code that adheres to the SOLID principles.
35
362. Facilitate and encourage the adherence to the best OOP and IoC practices.
37
383. Add as little runtime overhead as possible.
39
404. Provide a [state of the art development experience](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md).
41
42## Testimonies
43
44**[Nate Kohari](https://twitter.com/nkohari)** - Author of [Ninject](https://github.com/ninject/Ninject)
45
46> *"Nice work! I've taken a couple shots at creating DI frameworks for JavaScript and TypeScript, but the lack of RTTI really hinders things.*
47> *The ES7 metadata gets us part of the way there (as you've discovered). Keep up the great work!"*
48
49**[Michel Weststrate](https://twitter.com/mweststrate)** - Author of [MobX](https://github.com/mobxjs/mobx)
50> *Dependency injection like InversifyJS works nicely*
51
52## Some companies using InversifyJS
53
54[<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/)
55
56## 📦 Installation
57
58You can get the latest release and the type definitions using your preferred package manager:
59
60```sh
61> npm install inversify reflect-metadata --save
62> yarn add inversify reflect-metadata
63> pnpm add inversify reflect-metadata
64```
65
66> ❕**Hint!** If you want to use a more type-safe version of reflect-metadata, try [`@abraham/reflection`](https://www.npmjs.com/package/@abraham/reflection)
67
68The InversifyJS type definitions are included in the inversify npm package.
69
70> :warning: **Important!** InversifyJS requires TypeScript >= 4.4 and the `experimentalDecorators`, `emitDecoratorMetadata`, `types` and `lib`
71compilation options in your `tsconfig.json` file.
72
73```json
74{
75 "compilerOptions": {
76 "target": "es5",
77 "lib": ["es6"],
78 "types": ["reflect-metadata"],
79 "module": "commonjs",
80 "moduleResolution": "node",
81 "experimentalDecorators": true,
82 "emitDecoratorMetadata": true
83 }
84}
85```
86
87InversifyJS requires a modern JavaScript engine with support for:
88
89- [Reflect metadata](https://rbuckton.github.io/reflect-metadata/)
90- [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
91- [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))
92- [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))
93
94If your environment doesn't support one of these you will need to import a shim or polyfill.
95
96> :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).
97
98Check out the [Environment support and polyfills](https://github.com/inversify/InversifyJS/blob/master/wiki/environment.md)
99page in the wiki and the [Basic example](https://github.com/inversify/inversify-basic-example) to learn more.
100
101## The Basics
102Let’s take a look at the basic usage and APIs of InversifyJS with TypeScript:
103
104### Step 1: Declare your interfaces and types
105
106Our goal is to write code that adheres to the [dependency inversion principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle).
107This means that we should "depend upon Abstractions and do not depend upon concretions".
108Let's start by declaring some interfaces (abstractions).
109
110```ts
111// file interfaces.ts
112
113export interface Warrior {
114 fight(): string;
115 sneak(): string;
116}
117
118export interface Weapon {
119 hit(): string;
120}
121
122export interface ThrowableWeapon {
123 throw(): string;
124}
125```
126
127InversifyJS needs to use the type as identifiers at runtime. We use symbols as identifiers but you can also use classes and or string literals.
128
129```ts
130// file types.ts
131
132const TYPES = {
133 Warrior: Symbol.for("Warrior"),
134 Weapon: Symbol.for("Weapon"),
135 ThrowableWeapon: Symbol.for("ThrowableWeapon")
136};
137
138export { TYPES };
139
140```
141
142> **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).
143
144### Step 2: Declare dependencies using the `@injectable` & `@inject` decorators
145Let'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.
146
147When 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.
148
149```ts
150// file entities.ts
151
152import { injectable, inject } from "inversify";
153import "reflect-metadata";
154import { Weapon, ThrowableWeapon, Warrior } from "./interfaces";
155import { TYPES } from "./types";
156
157@injectable()
158class Katana implements Weapon {
159 public hit() {
160 return "cut!";
161 }
162}
163
164@injectable()
165class Shuriken implements ThrowableWeapon {
166 public throw() {
167 return "hit!";
168 }
169}
170
171@injectable()
172class Ninja implements Warrior {
173
174 private _katana: Weapon;
175 private _shuriken: ThrowableWeapon;
176
177 public constructor(
178 @inject(TYPES.Weapon) katana: Weapon,
179 @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
180 ) {
181 this._katana = katana;
182 this._shuriken = shuriken;
183 }
184
185 public fight() { return this._katana.hit(); }
186 public sneak() { return this._shuriken.throw(); }
187
188}
189
190export { Ninja, Katana, Shuriken };
191```
192
193If you prefer it you can use property injection instead of constructor injection so you don't have to declare the class constructor:
194
195```ts
196@injectable()
197class Ninja implements Warrior {
198 @inject(TYPES.Weapon) private _katana: Weapon;
199 @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon;
200 public fight() { return this._katana.hit(); }
201 public sneak() { return this._shuriken.throw(); }
202}
203```
204
205### Step 3: Create and configure a Container
206We recommend to do this in a file named `inversify.config.ts`. This is the only place in which there is some coupling.
207In the rest of your application your classes should be free of references to other classes.
208```ts
209// file inversify.config.ts
210
211import { Container } from "inversify";
212import { TYPES } from "./types";
213import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
214import { Ninja, Katana, Shuriken } from "./entities";
215
216const myContainer = new Container();
217myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
218myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
219myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);
220
221export { myContainer };
222```
223
224### Step 4: Resolve dependencies
225You can use the method `get<T>` from the `Container` class to resolve a dependency.
226Remember that you should do this only in your [composition root](http://blog.ploeh.dk/2011/07/28/CompositionRoot/)
227to avoid the [service locator anti-pattern](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/).
228
229```ts
230import { myContainer } from "./inversify.config";
231import { TYPES } from "./types";
232import { Warrior } from "./interfaces";
233
234const ninja = myContainer.get<Warrior>(TYPES.Warrior);
235
236expect(ninja.fight()).eql("cut!"); // true
237expect(ninja.sneak()).eql("hit!"); // true
238```
239
240As we can see the `Katana` and `Shuriken` were successfully resolved and injected into `Ninja`.
241
242InversifyJS supports ES5 and ES6 and can work without TypeScript.
243Head to the [**JavaScript example**](https://github.com/inversify/InversifyJS/blob/master/wiki/basic_js_example.md) to learn more!
244
245## 🚀 The InversifyJS Features and API
246Let's take a look to the InversifyJS features!
247
248- [Support for classes](https://github.com/inversify/InversifyJS/blob/master/wiki/classes_as_id.md)
249- [Support for Symbols](https://github.com/inversify/InversifyJS/blob/master/wiki/symbols_as_id.md)
250- [Container API](https://github.com/inversify/InversifyJS/blob/master/wiki/container_api.md)
251- [Declaring container modules](https://github.com/inversify/InversifyJS/blob/master/wiki/container_modules.md)
252- [Container snapshots](https://github.com/inversify/InversifyJS/blob/master/wiki/container_snapshots.md)
253- [Controlling the scope of the dependencies](https://github.com/inversify/InversifyJS/blob/master/wiki/scope.md)
254- [Declaring optional dependencies](https://github.com/inversify/InversifyJS/blob/master/wiki/optional_dependencies.md)
255- [Injecting a constant or dynamic value](https://github.com/inversify/InversifyJS/blob/master/wiki/value_injection.md)
256- [Injecting a class constructor](https://github.com/inversify/InversifyJS/blob/master/wiki/constructor_injection.md)
257- [Injecting a Factory](https://github.com/inversify/InversifyJS/blob/master/wiki/factory_injection.md)
258- [Auto factory](https://github.com/inversify/InversifyJS/blob/master/wiki/auto_factory.md)
259- [Auto named factory](https://github.com/inversify/InversifyJS/blob/master/wiki/auto_named_factory.md)
260- [Injecting a Provider (asynchronous Factory)](https://github.com/inversify/InversifyJS/blob/master/wiki/provider_injection.md)
261- [Activation handler](https://github.com/inversify/InversifyJS/blob/master/wiki/activation_handler.md)
262- [Deactivation handler](https://github.com/inversify/InversifyJS/blob/master/wiki/deactivation_handler.md)
263- [Post Construct decorator](https://github.com/inversify/InversifyJS/blob/master/wiki/post_construct.md)
264- [Middleware](https://github.com/inversify/InversifyJS/blob/master/wiki/middleware.md)
265- [Multi-injection](https://github.com/inversify/InversifyJS/blob/master/wiki/multi_injection.md)
266- [Tagged bindings](https://github.com/inversify/InversifyJS/blob/master/wiki/tagged_bindings.md)
267- [Create your own tag decorators](https://github.com/inversify/InversifyJS/blob/master/wiki/custom_tag_decorators.md)
268- [Named bindings](https://github.com/inversify/InversifyJS/blob/master/wiki/named_bindings.md)
269- [Default target](https://github.com/inversify/InversifyJS/blob/master/wiki/default_targets.md)
270- [Support for hierarchical DI systems](https://github.com/inversify/InversifyJS/blob/master/wiki/hierarchical_di.md)
271- [Contextual bindings & @targetName](https://github.com/inversify/InversifyJS/blob/master/wiki/contextual_bindings.md)
272- [Property injection](https://github.com/inversify/InversifyJS/blob/master/wiki/property_injection.md)
273- [Circular dependencies](https://github.com/inversify/InversifyJS/blob/master/wiki/circular_dependencies.md)
274- [Inheritance](https://github.com/inversify/InversifyJS/blob/master/wiki/inheritance.md)
275
276Please refer to the [wiki](https://github.com/inversify/InversifyJS/blob/master/wiki/readme.md) for additional details.
277
278## 🧩 Ecosystem
279In order to provide a state of the art development experience we are also working on:
280
281- [Middleware extensions](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#extensions).
282- [Development tools](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#development-tools).
283- [Examples](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#examples).
284
285Please refer to the [ecosystem wiki page](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md) to learn more.
286
287## Support
288If 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.
289
290If 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
291[wiki](https://github.com/inversify/InversifyJS/blob/master/wiki/readme.md) to learn more about InversifyJS internals.
292
293## Acknowledgements
294
295Thanks 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.
296
297## License
298
299License under the MIT License (MIT)
300
301Copyright © 2015-2017 [Remo H. Jansen](http://www.remojansen.com)
302
303Permission 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:
304
305The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
306
307THE 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.
308
309IN 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.