InversifyJS
A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
Top Related Projects
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
Lightweight dependency injection container for JavaScript/TypeScript
Simple yet powerful dependency injection tool for JavaScript and TypeScript.
Extremely powerful Inversion of Control (IoC) container for Node.JS
An addictive .NET IoC container
Quick Overview
InversifyJS is a powerful and lightweight inversion of control (IoC) container for JavaScript and TypeScript applications. It provides dependency injection capabilities, allowing developers to write more modular, testable, and maintainable code by decoupling components and managing their dependencies.
Pros
- Strongly-typed: Designed with TypeScript in mind, offering excellent type safety and IntelliSense support
- Flexible: Supports various binding techniques and lifecycle management options
- Decorators: Utilizes TypeScript decorators for clean and intuitive dependency injection syntax
- Extensible: Provides a plugin system for extending functionality and integrating with other libraries
Cons
- Learning curve: May require some time to understand IoC concepts and best practices
- Overhead: Adds a small runtime overhead and increases bundle size
- Limited browser support: Some features may not work in older browsers without polyfills
- Complexity: Can introduce additional complexity for smaller projects where manual dependency management might suffice
Code Examples
- Basic dependency injection:
import { injectable, inject, Container } from "inversify";
@injectable()
class Katana {
public hit() {
return "cut!";
}
}
@injectable()
class Ninja {
constructor(@inject("Weapon") private weapon: Katana) {}
public fight() {
return this.weapon.hit();
}
}
const container = new Container();
container.bind<Katana>("Weapon").to(Katana);
container.bind<Ninja>("Ninja").to(Ninja);
const ninja = container.get<Ninja>("Ninja");
console.log(ninja.fight()); // Output: "cut!"
- Named bindings:
import { injectable, inject, named, Container } from "inversify";
@injectable()
class Shuriken {
public throw() {
return "hit!";
}
}
@injectable()
class Ninja {
constructor(
@inject("Weapon") @named("throwable") private weapon: Shuriken
) {}
public throwWeapon() {
return this.weapon.throw();
}
}
const container = new Container();
container.bind<Shuriken>("Weapon").to(Shuriken).whenTargetNamed("throwable");
container.bind<Ninja>("Ninja").to(Ninja);
const ninja = container.get<Ninja>("Ninja");
console.log(ninja.throwWeapon()); // Output: "hit!"
- Factory bindings:
import { injectable, inject, Container } from "inversify";
interface Weapon {
use(): string;
}
@injectable()
class Katana implements Weapon {
public use() {
return "slash!";
}
}
@injectable()
class WeaponFactory {
create(type: string): Weapon {
if (type === "katana") {
return new Katana();
}
throw new Error("Unknown weapon type");
}
}
const container = new Container();
container.bind<WeaponFactory>("WeaponFactory").to(WeaponFactory);
container.bind<Weapon>("Weapon").toDynamicValue((context) => {
const factory = context.container.get<WeaponFactory>("WeaponFactory");
return factory.create("katana");
});
const weapon = container.get<Weapon>("Weapon");
console.log(weapon.use()); // Output: "slash!"
Getting Started
-
Install InversifyJS and its type definitions:
npm install inversify reflect-metadata npm install --save-dev @types/reflect-metadata
-
Configure TypeScript compiler options:
{ "compilerOptions": { "target": "es5", "lib": ["es6"], "types": ["reflect-metadata"], "module": "commonjs", "moduleResolution": "node", "experimentalDecorators": true, "emitDecoratorMetadata": true } }
-
Import reflect-metadata in your main file:
Competitor Comparisons
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
Pros of NestJS
- Full-featured framework with built-in support for various architectural patterns
- Extensive documentation and active community support
- Seamless integration with other libraries and databases
Cons of NestJS
- Steeper learning curve due to its opinionated structure
- Potentially overkill for smaller projects or microservices
- More boilerplate code compared to lightweight alternatives
Code Comparison
NestJS:
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats;
}
}
InversifyJS:
@injectable()
class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats;
}
}
The code structure is similar, but NestJS uses its own decorators and provides additional features out of the box, while InversifyJS focuses primarily on dependency injection.
Lightweight dependency injection container for JavaScript/TypeScript
Pros of TSyringe
- Lightweight and simple to use, with minimal setup required
- Supports both TypeScript and JavaScript projects
- Integrates well with other Microsoft tools and libraries
Cons of TSyringe
- Less feature-rich compared to InversifyJS
- Smaller community and ecosystem
- Limited documentation and examples available
Code Comparison
TSyringe:
import { injectable, inject, container } from "tsyringe";
@injectable()
class Service {
constructor(@inject("Logger") private logger: Logger) {}
}
InversifyJS:
import { injectable, inject, Container } from "inversify";
@injectable()
class Service {
constructor(@inject("Logger") private logger: Logger) {}
}
Both libraries use similar decorators for dependency injection, but InversifyJS offers more advanced features and configuration options. TSyringe provides a simpler API and is easier to set up for basic use cases, while InversifyJS offers greater flexibility and control over the dependency injection process.
TSyringe is a good choice for smaller projects or those already using Microsoft tools, while InversifyJS may be better suited for larger, more complex applications that require advanced dependency injection features and customization options.
Simple yet powerful dependency injection tool for JavaScript and TypeScript.
Pros of TypeDI
- Simpler API and easier to set up, with less boilerplate code
- Better integration with TypeScript decorators and metadata reflection
- Supports circular dependencies out of the box
Cons of TypeDI
- Less flexible configuration options compared to InversifyJS
- Smaller community and ecosystem
- Limited support for advanced IoC container features
Code Comparison
TypeDI:
import { Container, Service, Inject } from 'typedi';
@Service()
class UserService {
@Inject()
private database: Database;
}
InversifyJS:
import { injectable, inject, Container } from 'inversify';
@injectable()
class UserService {
constructor(@inject(Database) private database: Database) {}
}
Both TypeDI and InversifyJS are dependency injection containers for TypeScript applications. TypeDI offers a more straightforward approach with less setup required, making it easier for beginners to get started. It also provides better integration with TypeScript's decorator and metadata reflection features.
On the other hand, InversifyJS offers more advanced features and configuration options, making it suitable for complex applications with specific dependency injection requirements. It has a larger community and ecosystem, which can be beneficial for finding solutions to problems and third-party integrations.
The code comparison shows that TypeDI uses a more decorator-driven approach, while InversifyJS relies on constructor injection. Both achieve similar results, but TypeDI's syntax may be more intuitive for developers familiar with TypeScript decorators.
Extremely powerful Inversion of Control (IoC) container for Node.JS
Pros of Awilix
- Simpler API with less boilerplate code
- More flexible container configuration
- Better support for function injection and factory patterns
Cons of Awilix
- Less TypeScript-focused than InversifyJS
- Smaller community and ecosystem
- Fewer built-in decorators for advanced scenarios
Code Comparison
Awilix:
import { createContainer, asClass } from 'awilix';
const container = createContainer();
container.register({
userService: asClass(UserService)
});
InversifyJS:
import { Container, injectable, inject } from 'inversify';
@injectable()
class UserService {
constructor(@inject(TYPES.Database) private database: Database) {}
}
const container = new Container();
container.bind<UserService>(TYPES.UserService).to(UserService);
Both Awilix and InversifyJS are popular dependency injection containers for JavaScript/TypeScript applications. Awilix offers a more straightforward API and flexible configuration options, making it easier to set up and use for simpler projects. It also provides better support for function injection and factory patterns.
On the other hand, InversifyJS is more TypeScript-focused, offering stronger type safety and decorators for advanced scenarios. It has a larger community and ecosystem, which can be beneficial for larger projects or teams requiring more extensive support and resources.
The code comparison demonstrates the difference in syntax and approach between the two libraries, with Awilix using a more concise and flexible registration method, while InversifyJS relies on decorators and explicit type bindings.
An addictive .NET IoC container
Pros of Autofac
- Mature and well-established in the .NET ecosystem
- Extensive documentation and community support
- Supports advanced scenarios like child containers and lifetime scopes
Cons of Autofac
- Limited to .NET platforms
- Steeper learning curve for beginners
- Slightly more verbose configuration compared to InversifyJS
Code Comparison
Autofac (C#):
var builder = new ContainerBuilder();
builder.RegisterType<MyService>().As<IService>();
var container = builder.Build();
var service = container.Resolve<IService>();
InversifyJS (TypeScript):
const container = new Container();
container.bind<IService>(TYPES.IService).to(MyService);
const service = container.get<IService>(TYPES.IService);
Both Autofac and InversifyJS are powerful dependency injection containers for their respective ecosystems. Autofac excels in the .NET world with its maturity and extensive features, while InversifyJS provides a more lightweight and flexible solution for TypeScript and JavaScript projects. The choice between them largely depends on the target platform and specific project requirements.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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:
> npm install inversify reflect-metadata --save
> yarn add inversify reflect-metadata
> pnpm add inversify reflect-metadata
âHint! If you want to use a more type-safe version of reflect-metadata, try
@abraham/reflection
The InversifyJS type definitions are included in the inversify npm package.
:warning: Important! InversifyJS requires TypeScript >= 4.4 and the
experimentalDecorators
,emitDecoratorMetadata
,types
andlib
compilation options in yourtsconfig.json
file.
{
"compilerOptions": {
"target": "es5",
"lib": ["es6"],
"types": ["reflect-metadata"],
"module": "commonjs",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
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.
: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.
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).
// file interfaces.ts
export interface Warrior {
fight(): string;
sneak(): string;
}
export interface Weapon {
hit(): string;
}
export interface ThrowableWeapon {
throw(): string;
}
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)
// file types.ts
const TYPES = {
Warrior: Symbol.for("Warrior"),
Weapon: Symbol.for("Weapon"),
ThrowableWeapon: Symbol.for("ThrowableWeapon")
};
export { TYPES };
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. All the classes must be annotated 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.
// file entities.ts
import { injectable, inject } from "inversify";
import "reflect-metadata";
import { Weapon, ThrowableWeapon, Warrior } from "./interfaces";
import { TYPES } from "./types";
@injectable()
class Katana implements Weapon {
public hit() {
return "cut!";
}
}
@injectable()
class Shuriken implements ThrowableWeapon {
public throw() {
return "hit!";
}
}
@injectable()
class Ninja implements Warrior {
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(
@inject(TYPES.Weapon) katana: Weapon,
@inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); }
public sneak() { return this._shuriken.throw(); }
}
export { 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:
@injectable()
class Ninja implements Warrior {
@inject(TYPES.Weapon) private _katana: Weapon;
@inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon;
public fight() { return this._katana.hit(); }
public sneak() { return this._shuriken.throw(); }
}
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.
// file inversify.config.ts
import { Container } from "inversify";
import { TYPES } from "./types";
import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
import { Ninja, Katana, Shuriken } from "./entities";
const myContainer = new Container();
myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);
export { 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.
import { myContainer } from "./inversify.config";
import { TYPES } from "./types";
import { Warrior } from "./interfaces";
const ninja = myContainer.get<Warrior>(TYPES.Warrior);
expect(ninja.fight()).eql("cut!"); // true
expect(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.
Top Related Projects
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
Lightweight dependency injection container for JavaScript/TypeScript
Simple yet powerful dependency injection tool for JavaScript and TypeScript.
Extremely powerful Inversion of Control (IoC) container for Node.JS
An addictive .NET IoC container
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot