A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
Installations
npm install inversify
Developer Guide
Typescript
Yes
Module System
CommonJS, ESM
Node Version
22.12.0
NPM Version
11.0.0
Score
99.2
Supply Chain
99.2
Quality
97
Maintenance
100
Vulnerability
99.6
License
Releases
Contributors
Languages
TypeScript (98.7%)
JavaScript (1.3%)
Developer
Download Statistics
Total Downloads
181,649,769
Last Day
85,436
Last Week
890,283
Last Month
4,740,541
Last Year
44,583,469
GitHub Statistics
11,413 Stars
1,556 Commits
723 Forks
135 Watching
2 Branches
120 Contributors
Bundle Size
41.90 kB
Minified
10.89 kB
Minified + Gzipped
Package Meta Information
Latest Version
6.2.1
Package Id
inversify@6.2.1
Unpacked Size
486.36 kB
Size
100.16 kB
File Count
222
NPM Version
11.0.0
Node Version
22.12.0
Publised On
19 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
181,649,769
Last day
-58%
85,436
Compared to previous day
Last week
-21.5%
890,283
Compared to previous week
Last month
1.7%
4,740,541
Compared to previous month
Last year
24.2%
44,583,469
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Peer Dependencies
1
Dev Dependencies
23
InversifyJS
A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
About
InversifyJS is a lightweight inversion of control (IoC) container for TypeScript and JavaScript apps. An IoC container uses a class constructor to identify and inject its dependencies. InversifyJS has a friendly API and encourages the usage of the best OOP and IoC practices.
Motivation
JavaScript now supports object oriented (OO) programming with class based inheritance. These features are great but the truth is that they are also dangerous.
We need a good OO design (SOLID, Composite Reuse, etc.) to protect ourselves from these threats. The problem is that OO design is difficult and that is exactly why we created InversifyJS.
InversifyJS is a tool that helps JavaScript developers write code with good OO design.
Philosophy
InversifyJS has been developed with 4 main goals:
-
Allow JavaScript developers to write code that adheres to the SOLID principles.
-
Facilitate and encourage the adherence to the best OOP and IoC practices.
-
Add as little runtime overhead as possible.
-
Provide a state of the art development experience.
Testimonies
Nate Kohari - Author of Ninject
"Nice work! I've taken a couple shots at creating DI frameworks for JavaScript and TypeScript, but the lack of RTTI really hinders things. The ES7 metadata gets us part of the way there (as you've discovered). Keep up the great work!"
Michel Weststrate - Author of MobX
Dependency injection like InversifyJS works nicely
Some companies using InversifyJS
📦 Installation
You can get the latest release and the type definitions using your preferred package manager:
1> npm install inversify reflect-metadata --save 2> yarn add inversify reflect-metadata 3> pnpm add inversify reflect-metadata
reflect-metadata
will be automatically imported by inversify.
The InversifyJS type definitions are included in the inversify npm package.
:warning: Important! InversifyJS requires TypeScript >= 4.4 and the
experimentalDecorators
,emitDecoratorMetadata
, compilation options in yourtsconfig.json
file.
1{ 2 "compilerOptions": { 3 "experimentalDecorators": true, 4 "emitDecoratorMetadata": true 5 } 6}
InversifyJS requires a modern JavaScript engine with support for:
- Reflect metadata
- Map
- Promise (Only required if using provider injection)
- Proxy (Only required if using activation handlers)
If your environment doesn't support one of these you will need to import a shim or polyfill.
Check out the Environment support and polyfills page in the wiki and the Basic example to learn more.
The Basics
Let’s take a look at the basic usage and APIs of InversifyJS with TypeScript:
Step 1: Declare your interfaces and types
Our goal is to write code that adheres to the dependency inversion principle. This means that we should "depend upon Abstractions and do not depend upon concretions". Let's start by declaring some interfaces (abstractions).
1// file interfaces.ts 2 3export interface Warrior { 4 fight(): string; 5 sneak(): string; 6} 7 8export interface Weapon { 9 hit(): string; 10} 11 12export interface ThrowableWeapon { 13 throw(): string; 14}
InversifyJS needs to use the type as identifiers at runtime. We use symbols as identifiers but you can also use classes and or string literals.
PLEASE MAKE SURE TO PLACE THIS TYPES DECLARATION IN A SEPARATE FILE. (see bug #1455)
1// file types.ts
2
3const TYPES = {
4 Warrior: Symbol.for("Warrior"),
5 Weapon: Symbol.for("Weapon"),
6 ThrowableWeapon: Symbol.for("ThrowableWeapon")
7};
8
9export { TYPES };
10
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).
Step 2: Declare dependencies using the @injectable
& @inject
decorators
Let's continue by declaring some classes (concretions). The classes are implementations of the interfaces that we just declared. We will annotate them with the @injectable
decorator.
When 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.
1// file entities.ts 2 3import { injectable, inject } from "inversify"; 4import { Weapon, ThrowableWeapon, Warrior } from "./interfaces"; 5import { TYPES } from "./types"; 6 7@injectable() 8class Katana implements Weapon { 9 public hit() { 10 return "cut!"; 11 } 12} 13 14@injectable() 15class Shuriken implements ThrowableWeapon { 16 public throw() { 17 return "hit!"; 18 } 19} 20 21@injectable() 22class Ninja implements Warrior { 23 24 private _katana: Weapon; 25 private _shuriken: ThrowableWeapon; 26 27 constructor( 28 @inject(TYPES.Weapon) katana: Weapon, 29 @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon 30 ) { 31 this._katana = katana; 32 this._shuriken = shuriken; 33 } 34 35 public fight() { return this._katana.hit(); } 36 public sneak() { return this._shuriken.throw(); } 37 38} 39 40export { Ninja, Katana, Shuriken };
If you prefer it you can use property injection instead of constructor injection so you don't have to declare the class constructor:
1@injectable() 2class Ninja implements Warrior { 3 @inject(TYPES.Weapon) private _katana: Weapon; 4 @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon; 5 public fight() { return this._katana.hit(); } 6 public sneak() { return this._shuriken.throw(); } 7}
Step 3: Create and configure a Container
We recommend to do this in a file named inversify.config.ts
. This is the only place in which there is some coupling.
In the rest of your application your classes should be free of references to other classes.
1// file inversify.config.ts 2 3import { Container } from "inversify"; 4import { TYPES } from "./types"; 5import { Warrior, Weapon, ThrowableWeapon } from "./interfaces"; 6import { Ninja, Katana, Shuriken } from "./entities"; 7 8const myContainer = new Container(); 9myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja); 10myContainer.bind<Weapon>(TYPES.Weapon).to(Katana); 11myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken); 12 13export { myContainer };
Step 4: Resolve dependencies
You can use the method get<T>
from the Container
class to resolve a dependency.
Remember that you should do this only in your composition root
to avoid the service locator anti-pattern.
1import { myContainer } from "./inversify.config"; 2import { TYPES } from "./types"; 3import { Warrior } from "./interfaces"; 4 5const ninja = myContainer.get<Warrior>(TYPES.Warrior); 6 7expect(ninja.fight()).eql("cut!"); // true 8expect(ninja.sneak()).eql("hit!"); // true
As we can see the Katana
and Shuriken
were successfully resolved and injected into Ninja
.
InversifyJS supports ES5 and ES6 and can work without TypeScript. Head to the JavaScript example to learn more!
🚀 The InversifyJS Features and API
Let's take a look to the InversifyJS features!
- Support for classes
- Support for Symbols
- Container API
- Declaring container modules
- Container snapshots
- Controlling the scope of the dependencies
- Declaring optional dependencies
- Injecting a constant or dynamic value
- Injecting a class constructor
- Injecting a Factory
- Auto factory
- Auto named factory
- Injecting a Provider (asynchronous Factory)
- Activation handler
- Deactivation handler
- Post Construct decorator
- Middleware
- Multi-injection
- Tagged bindings
- Create your own tag decorators
- Named bindings
- Default target
- Support for hierarchical DI systems
- Contextual bindings & @targetName
- Property injection
- Circular dependencies
- Inheritance
Please refer to the wiki for additional details.
🧩 Ecosystem
In order to provide a state of the art development experience we are also working on:
Please refer to the ecosystem wiki page to learn more.
Support
If you are experience any kind of issues we will be happy to help. You can report an issue using the issues page or the chat. You can also ask questions at Stack overflow using the inversifyjs
tag.
If 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. You can check out the wiki to learn more about InversifyJS internals.
Acknowledgements
Thanks a lot to all the 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.
License
License under the MIT License (MIT)
Copyright © 2015-2017 Remo H. Jansen
Permission 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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE 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.
IN 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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
30 commit(s) and 29 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
dependency not pinned by hash detected -- score normalized to 5
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/inversify/InversifyJS/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/inversify/InversifyJS/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:48: update your workflow using https://app.stepsecurity.io/secureworkflow/inversify/InversifyJS/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:52: update your workflow using https://app.stepsecurity.io/secureworkflow/inversify/InversifyJS/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:65: update your workflow using https://app.stepsecurity.io/secureworkflow/inversify/InversifyJS/ci.yml/master?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 2 out of 2 npmCommand dependencies pinned
Reason
Found 1/21 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
5.2
/10
Last Scanned on 2024-12-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to inversify
inversify-inject-decorators
Lazy evaluated property injection decorators for InversifyJS
inversify-binding-decorators
An utility that allows developers to declare InversifyJS bindings using ES2016 decorators
inversify-props
Wrapper to use inversify as property decorator with TypeScript, useful for component libraries like Vue, React or LitElement
mana-syringe
IoC library for mana, easily to use.