Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

inversify

inversify4.6mMIT6.2.1TypeScript support: included

A powerful and lightweight inversion of control container for JavaScript and Node.js apps powered by TypeScript.

dependency injection, dependency inversion, di, inversion of control container, ioc, javascript, node, typescript

readme

NPM version NPM Downloads Docs Codecov

GitHub stars Discord Server

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:

  1. Allow JavaScript developers to write code that adheres to the SOLID principles.

  2. Facilitate and encourage the adherence to the best OOP and IoC practices.

  3. Add as little runtime overhead as possible.

  4. 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

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 your tsconfig.json file.

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

InversifyJS requires a modern JavaScript engine with support for:

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).

// 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. 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.

// file entities.ts

import { injectable, inject } from "inversify";
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;

    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!

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.

changelog

Changelog

All notable changes to this project from 5.0.0 forward will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

Added

Changed

Fixed

[6.2.1]

Fixed

  • Added missing LazyServiceIdentifer.

[6.2.0]

Added

  • Added interfaces.GetAllOptions.

Changed

  • Updated container.getAll with options optional param.
  • Updated container.getAllAsync with options optional param.
  • Updated interfaces.NextArgs with optional isOptional param.
  • Updated container with tryGet.
  • Updated container with tryGetAsync.
  • Updated container with tryGetTagged.
  • Updated container with tryGetTaggedAsync.
  • Updated container with tryGetNamed.
  • Updated container with tryGetNamedAsync.
  • Updated container with tryGetAll.
  • Updated container with tryGetAllAsync.
  • Updated container with tryGetAllTagged.
  • Updated container with tryGetAllTaggedAsync.
  • Updated container with tryGetAllNamed.
  • Updated container with tryGetAllNamedAsync.

[6.2.0-beta.1]

Added

Changed

  • Updated interfaces.NextArgs with optional isOptional param.
  • Updated container with tryGet.
  • Updated container with tryGetAsync.
  • Updated container with tryGetTagged.
  • Updated container with tryGetTaggedAsync.
  • Updated container with tryGetNamed.
  • Updated container with tryGetNamedAsync.
  • Updated container with tryGetAll.
  • Updated container with tryGetAllAsync.
  • Updated container with tryGetAllTagged.
  • Updated container with tryGetAllTaggedAsync.
  • Updated container with tryGetAllNamed.
  • Updated container with tryGetAllNamedAsync.

Fixed

[6.2.0-beta.0]

Added

  • Added interfaces.GetAllOptions.

Changed

  • Updated container.getAll with options optional param.
  • Updated container.getAllAsync with options optional param.

Fixed

[6.1.6]

Fixed

  • Fixed unexpected property access while running planning checks on injected base types.
  • Updated ESM sourcemaps to refelct the right source code files.

[6.1.5]

Changed

  • Updated library to import reflect-metadata. Importing reflect-metadata before bootstraping a module in the userland is no longer required.

Fixed

  • Updated ESM build to provide proper types regardless of the ts resolution module strategy in the userland.
  • Fixed container to properly resolve async .toService bindings.
  • Fixed .toService binding to properly disable caching any values.

[6.1.5-beta.2]

Fixed

  • Updated ESM bundled types to solve circularly referenced types.

[6.1.5-beta.1]

Fixed

  • Updated ESM build to provide proper types regardless of the ts resolution module strategy in the userland.

[6.1.5-beta.0]

Changed

  • Updated library to import reflect-metadata. Importing reflect-metadata before bootstraping a module in the userland is no longer required.

Fixed

  • Fixed container to properly resolve async .toService bindings.
  • Fixed .toService binding to properly disable caching any values.

[6.1.4]

Changed

  • Updated planner with better error description when a binding can not be properly resolved.

Fixed

  • Updated container to allow deactivating singleton undefined values.
  • Updated ESM build to be compatible with both bundler and NodeJS module resolution algorithms.

[6.1.4-beta.1]

Fixed

  • Updated ESM build to be compatible with both bundler and NodeJS module resolution algorithms.

[6.1.4-beta.0]

Changed

  • Updated planner with better error description when a binding can not be properly resolved.

[6.1.3]

Fixed

  • Updated ESM build with missing types.

[6.1.2]

Changed

  • Updated package.json to include the exports field for better bundler support.

Fixed

  • Updated fetch metadata flows with better error descriptions.

[6.1.2-beta.1]

Changed

  • Updated package.json to include the exports field for better bundler support.

[6.1.2-beta.0]

Fixed

  • Updated fetch metadata flows with better error descriptions.

[6.1.1]

Fixed

  • Bumped @inversifyjs/common and @inversifyjs/core fixing wrong dev engines constraints.

[6.1.0]

Changed

  • Updated ServiceIdentifier to rely on Function instead of Abstract<T>.

Fixed

  • Fixed Target.getNameTag with the right type: number | string | symbol.
  • Fixed interfaces.ModuleActivationStore.addDeactivation to enforce serviceIdentifier and onDeactivation are consistent.
  • Fixed interfaces.ModuleActivationStore.addActivation to enforce serviceIdentifier and onDeactivation are consistent.

[6.0.3]

Fixed

property injection tagged as @optional no longer overrides default values with undefined. Updated targetName to be a valid typescript@5 decorator.

[6.0.2]

Added

Brought tests up to 100% Code Coverage

Changed

LazyIdentfier Tests Removed browser test pipeline, browserify, karma (#1542) Update all dependencies except typescript (#1531)

Fixed

Less than 100% code coverage Use default class property for @optional injected properties (#1467) Remove circular import (#1516) Fix strict type checking on @unmanaged decorator (#1499) Fix typo (LazyServiceIdentifer -> LazyServiceIdentifier) (#1483) Fix typo (circular dependency error message) (#1485)

[6.0.1] - 2021-10-14

Added

  • add API method for check dependency only in current container
  • createTaggedDecorator #1343
  • Async bindings #1132
  • Async binding resolution (getAllAsync, getAllNamedAsync, getAllTaggedAsync, getAsync, getNamedAsync, getTaggedAsync, rebindAsync, unbindAsync, unbindAllAsync, unloadAsync) #1132
  • Global onActivation / onDeactivation #1132
  • Parent/Child onActivation / onDeactivation #1132
  • Module onActivation / onDeactivation #1132
  • Added @preDestroy decorator #1132

Changed

  • @postConstruct can target an asyncronous function #1132
  • Singleton scoped services cache resolved values once the result promise is fulfilled #1320

Fixed

  • only inject decorator can be applied to setters #1342
  • Container.resolve should resolve in that container #1338

[5.1.1] - 2021-04-25

-Fix pre-publish for build artifacts

[5.1.0] - 2021-04-25

Added

  • Upgrade information for v4.x to v5.x

Changed

  • Update BindingToSyntax with .toAutoNamedFactory().

Fixed

  • Fix Target.isTagged() to exclude optional from tag injections #1190.
  • Update toConstructor, toFactory, toFunction, toAutoFactory, toProvider and toConstantValue to have singleton scope #1297.
  • Fix injection on optional properties when targeting ES6 #928

[5.0.1] - 2018-10-17

Added

  • Updating constructor injection wiki document with concrete injection example #922

Changed

  • Change GUID to incremented counter for better performance #882

Fixed

  • fix broken compilation by adding .toString() so symbols serialization #893
  • Fix problem with applying options on Container.resolve (fix #914) #915
  • Fixed documentation issues

[4.14.0] - 2018-10-16

Deprecated - Replaced by 5.0.1