Git Product home page Git Product logo

es6ioc's Introduction

es6ioc

ES6 Dependency Injection container

Languages

Motivation

  1. Implement DI principles
  2. Testability
  3. Customization by configuration file

##Dependency Annotation

Similar to AngularJs 1.x you must to annotate your ES6 classes with $inject property that container knows what types to inject into constructor.

class Provider {
    constructor(connectionString, logger) {
        this.connectionString = connectionString;
        this.logger = logger;
    }
    getData() {
    }
}
Provider.$inject = ['connectionString', 'logger'];

Register

To define your types in container you have to use 'registerType' method. Method tells the container instantiate object that requires by concrete injection. To map types container uses string aliases.

Example:

import IoC from ‘ioc.js’

const ioc = new IoC();
ioc.registerType('connectionString', 'http://api.com');
ioc.registerType('logger', Logger);
ioc.registerType('provider', Provider);

Resolve

To instatiate concrete object and it's dependencies you have to use 'resolve' method.

let logic = ioc.resolve('logic');

Note that object do not instantiated directly, rather you just say: "Hey, ioc give me the 'logic'". And container first construct object dependencies and then passes them to required object constructor.

Цели

  1. Реализация принципов DI
  2. Повышение тестируемости кода
  3. Возможность конфигурирования приложения

Опеределение зависимостей

Также как в AngularJs 1.x вам нужно определить статическое свойство $inject. Это позволить IoC контейнеру определить какие зависимости требует ваш класс.

class Provider {
    constructor(connectionString, logger) {
        this.connectionString = connectionString;
        this.logger = logger;
    }
    getData() {
    }
}
Provider.$inject = ['connectionString', 'logger'];

Регистрация зависимостей

Первым делом необходиму указать контейнеру соотвествие имени зависимости и класса реализации.

Пример:

import IoC from ‘ioc.js’

const ioc = new IoC();

ioc.registerType('logger', Logger);

Создание экземпляров объектов

Для создания конкретного объекта необходимо вызвать метод resolve

let logic = ioc.resolve('logic');

Обратите внимание, что явного создания зависимостей не происходит. Вы просто говорите контейнеру: "Создай мне зависимость logic". При этом сначала будут созданы все зависимости, а затем сам запрашиваемый объект.

es6ioc's People

Contributors

robert-sz avatar

Stargazers

Valeriy Dmitriev avatar Гайфуллин Ильшат avatar David avatar  avatar  avatar Salvador Moret avatar

Watchers

James Cloos avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.