All Projects → inversify → Inversifyjs

inversify / Inversifyjs

Licence: mit
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.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to Inversifyjs

vue-ioc
IoC and DI for Vue powered by InversifyJS and inspired by Angular Module syntactic sugar.
Stars: ✭ 39 (-99.54%)
Mutual labels:  ioc, dependency-injection, inversifyjs
granitic
Web/micro-services and IoC framework for Golang developers
Stars: ✭ 32 (-99.62%)
Mutual labels:  ioc, dependency-injection
diod
A very opinionated inversion of control (IoC) container and dependency injector for Typescript, Node.js or browser apps.
Stars: ✭ 36 (-99.57%)
Mutual labels:  ioc, dependency-injection
Blog.core
💖 ASP.NET Core 6.0 全家桶教程,前后端分离后端接口,vue教程姊妹篇,官方文档:
Stars: ✭ 3,542 (-57.83%)
Mutual labels:  dependency-injection, ioc
fusion
A simple automated dependency injection library for TypeScript, supporting React class and functional components.
Stars: ✭ 18 (-99.79%)
Mutual labels:  ioc, dependency-injection
alpha-dic
Powerful dependency injection container for node.js
Stars: ✭ 27 (-99.68%)
Mutual labels:  ioc, dependency-injection
Quicklib
Quick development library (AutoMapper, LinQ, IOC Dependency Injection, MemoryCache, Scheduled tasks, Config, Serializers, etc) with crossplatform support for Delphi/Firemonkey (Windows,Linux,OSX/IOS/Android) and freepascal (Windows/Linux).
Stars: ✭ 274 (-96.74%)
Mutual labels:  dependency-injection, ioc
ThunderboltIoc
One of the very first IoC frameworks for .Net that has no reflection. An IoC that casts its services before thunder casts its bolts.
Stars: ✭ 40 (-99.52%)
Mutual labels:  ioc, dependency-injection
Ditranquillity
Dependency injection for iOS (Swift)
Stars: ✭ 317 (-96.23%)
Mutual labels:  dependency-injection, ioc
Loopback Next
LoopBack makes it easy to build modern API applications that require complex integrations.
Stars: ✭ 3,972 (-52.71%)
Mutual labels:  dependency-injection, ioc
Typescript Ioc
A Lightweight annotation-based dependency injection container for typescript.
Stars: ✭ 427 (-94.92%)
Mutual labels:  dependency-injection, ioc
Zenject-2019
Dependency Injection Framework for Unity3D
Stars: ✭ 2,567 (-69.44%)
Mutual labels:  ioc, dependency-injection
telephone-ts
Telephone-ts: The "Event Emitter-less" TypeScript Event Architecture.
Stars: ✭ 22 (-99.74%)
Mutual labels:  dependency-injection, inversifyjs
Hangfire.StructureMap
Hangfire background job activator based on the StructureMap IoC container
Stars: ✭ 16 (-99.81%)
Mutual labels:  ioc, dependency-injection
nodejs-boilerplate
Clean Architecture for node.js projects (Typescript + Express + TypeORM + Typedi)
Stars: ✭ 199 (-97.63%)
Mutual labels:  dependency-injection, inversifyjs
brisk-ioc
fast light brisk ioc/di container on nodejs; Node下快速 轻量的IoC/DI容器,依赖注入,配合装饰器使用
Stars: ✭ 12 (-99.86%)
Mutual labels:  ioc, dependency-injection
redi
💉 A dependency injection library for TypeScript & JavaScript, along with a binding for React.
Stars: ✭ 29 (-99.65%)
Mutual labels:  ioc, dependency-injection
Shiftscheduler
A boilerplate ASP.NET Core project, including a sample employee shift scheduler app
Stars: ✭ 5 (-99.94%)
Mutual labels:  dependency-injection, ioc
Kangaru
🦘 A dependency injection container for C++11, C++14 and later
Stars: ✭ 297 (-96.46%)
Mutual labels:  dependency-injection, ioc
Go Spring
基于 IoC 的 Go 后端一站式开发框架 🚀
Stars: ✭ 744 (-91.14%)
Mutual labels:  dependency-injection, ioc

InversifyJS

Join the chat at https://discord.gg/jXcMagAPnm Build Status

Test Coverage npm version Dependencies img img Known Vulnerabilities Twitter Follow

NPM NPM

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 npm:

$ npm install inversify reflect-metadata --save

The InversifyJS type definitions are included in the inversify npm package.

⚠️ Important! InversifyJS requires TypeScript >= 4.4 and the experimentalDecorators, emitDecoratorMetadata, types and lib compilation options in your tsconfig.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:

If your environment doesn't support one of these you will need to import a shim or polyfill.

⚠️ 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.

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

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].