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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

深入浅出HTML5编程

深入浅出HTML5编程

弗里曼 (Eric Friiman)、罗布森 (Elisabdth Robson) / 东南大学出版社 / 2012-4 / 98.00元

《深入浅出HTML5编程(影印版)(英文)》就是你的特快车票,它可以带你学习如何使用今天的标准同时也会是明日的最佳实践来搭建Web应用。同时,你会了解HTML5的新API的基本知识,甚至你还会弄明白这些API是如何与你的网页进行交互,JaVaScript如何为它们提供动力,以及你如何使用它们来搭建能够打动你的老板并且吸引你的朋友的Web应用。一起来看看 《深入浅出HTML5编程》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换