Dependency Injections in TypeScript

栏目: IT技术 · 发布时间: 4年前

内容简介:TypeScript Injections is a dependency injection library, which move responsibility from producer to customer.TypeScript Injections is a one of many variations about implementation of Inversion of Control (IoC). Main features are:You can get the latest rele

TypeScript Injections is a dependency injection library, which move responsibility from producer to customer.

Introduction

TypeScript Injections is a one of many variations about implementation of Inversion of Control (IoC). Main features are:

  1. Support for popular libraries and frameworks (e.g. Vue.js) Many libraries, which implements IoC requires classes to work and resolving dependency can be do only in constructor params, but many libraries and frameworks (e.g. Vue.js) operand on object "non-class", and we don't have access to the constructor. For this reason some libraries, which implements IoC are useless, because they can not be used with popular frameworks and libraries.

    This library supports object "non-class" and resolving dependency can be do anywhere and this feature resolving previously mentioned trouble.

  2. Partial support for Dependency Injection Principle (DIP) Because of how TypeScript works, there is not exists technical possibility to full implementation of DIP, because interfaces not exists at the runtime, but they are the basis of DIP. For this reason all libraries of this type must compromise, when want to supports DIP. In this library these compromise is using abstract class instead interfaces. More about this you can read inPartial support for Dependency Injection Principle (DIP)section.

  3. Responsibility for resolving dependency is moved from producer to customer. Many libraries uses for dependency injections work in such a way that the class decide that can be resolving by dependency (generally via @injectable decorator). In my opinion, that implementation is a broken of DIP rule and in this library i moved thar responsibility into customer using Resolve method.

  4. Singleton is transparent. Management of singleton is moved into definition and that has 2 important benefits:

    • Singleton is transparent - customer doesn't know he use singleton - he use object same as using object which is not singleton
    • Management of instances is moved into library and thus classes no longer needs manage of own instance - single-responsibility principle (SRP) rule is kept.

Installation

You can get the latest release using npm:

$ npm install typescript-injections --save

Basic usage

The biggest change is creating instances of classes - in this case responsibility is moved into library and we will create instanceof by Resolve method instead of operator new .

Library usage is included in 2 steps: define dependencies and resolving them.

Inject class

Let's assume these code:

class Connection {
    public ping(): void {

    }
}
class MySQLConnection extends Connection {
    public ping(): void {
        super.ping();
        // some stuff
    }
}

Now we're go to define dependencies - injection of class in this case:

import { Define, Inject } from "typescript-injections";
import Connection from "./Connection";
import MySQLConnection from "./MySQLConnection";

Define([
    Inject({
        type: Connection,
        to: MySQLConnection,
    }),
]);

And place, where we need Connection intstance - we don't need to know, it is MySQLConnection or, e.g. SQLiteConnection - we just want Connection instance:

import { Resolve } from "typescript-injections";
import Connection from "./Connection";

const connection = Resolve(this, Connection); // connection instanceof MySQLConnection

As you see - we won't import MySqlConnection - our code dependy only on Connection .

Inject property

In some cases we need to inject some properties into object.

class MySQLConnection extends Connection {
    public hostname: string | null = null;
    public login: string | null = null;
    public password: string | null = null;
    public database: string | null = null;

    public ping(): void {
        super.ping();
        // some stuff
    }
}

Place, where we resolving dependencies don't know about MySQLConnection and him properties. Inject properties can be do in the same place, where was inject class:

import { Define, InjectProps } from "typescript-injections";
import Connection from "./Connection";
import MySQLConnection from "./MySQLConnection";

Define([
    Inject({
        type: Connection,
        to: MySQLConnection,
    }),
    InjectProps({
        type: MySQLConnection,
        props: {
            hostname: "localhost",
            login: "root",
            password: "",
            database: "main",
        },
    }),
]);

Singletonize

As you probably seen - library creates new instance of MySQLConnection every time, when you code want access to this. In some cases, that behavior is unexpected, as in that case - we want have only once connection to database.

To Singletonize Connection, we must add new definition into already existing definitions:

import { Define, InjectProps, Singletonize } from "typescript-injections";
import Connection from "./Connection";

Define([
    Inject({
        type: Connection,
        to: MySQLConnection,
    }),
    InjectProps({
        type: MySQLConnection,
        props: {
            hostname: "localhost",
            login: "root",
            password: "",
            database: "main",
        },
    }),
    Singletonize({
        type: MySQLConnection,
    }),
]);

That definition gives us sure than code Resolve(this, Connection) every time gives us exactly same instance of Connection .

Partial support for Dependency Injection Principle (DIP)

As I said before - we can not implement full implementation of DIP, because interfaces in TypeScript doesn't exists at the runtime. My proposition of compromise is a using abstract classes, which resolve that problem, because abstract class exists at the runtime.

For Example:

abstract class Connection {
    public abstract ping(): void;
}
class MySQLConnection extends Connection {
    public ping(): void {
        // some stuff
    }
}

And next, we can define that dependency:

import { Define, Inject } from "typescript-injections";
import Connection from "./Connection";
import MySQLConnection from "./MySQLConnection";

Define([
    Inject({
        type: Connection,
        to: MySQLConnection,
    }),
]);

Ofcourse, that compromise has benefits and disadvantages. Undisputed benefit is a automatically types in TypeScript - there's no need to use as construct.

And here are the disadvantages:

  1. If you do not define dependency from abstract class to some final class, then... library creates instance of abstract class. At the runtime we can't detect is given class is abstract or "normal".
  2. Abstract class is some between "normal class" and interface and can has implementation, so if somebody will really wants broke DIP rule - they can do this and library can not do nothing with that fact.

License

MIT


以上所述就是小编给大家介绍的《Dependency Injections in TypeScript》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

极简算法史:从数学到机器的故事

极简算法史:从数学到机器的故事

[法] 吕克•德•布拉班迪尔 / 任轶 / 人民邮电出版社 / 2019-1 / 39.00元

数学、逻辑学、计算机科学三大领域实属一家,彼此成就,彼此影响。从古希腊哲学到“无所不能”的计算机,数字、计算、推理这些貌似简单的概念在三千年里融汇、碰撞。如何将逻辑赋予数学意义?如何从简单运算走向复杂智慧?这背后充满了人类智慧的闪光:从柏拉图、莱布尼茨、罗素、香农到图灵都试图从数学公式中证明推理的合理性,缔造完美的思维体系。他们是凭天赋制胜,还是鲁莽地大胆一搏?本书描绘了一场人类探索数学、算法与逻......一起来看看 《极简算法史:从数学到机器的故事》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具