Dependency Injections in TypeScript

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

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

查看所有标签

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

Java语言程序设计

Java语言程序设计

(美) Y. Daniel Liang / 李娜 / 机械工业出版社 / 2011-6 / 75.00元

本书是Java语言的经典教材,多年来畅销不衰。本书全面整合了Java 6的特性,采用“基础优先,问题驱动”的教学方式,循序渐进地介绍了程序设计基础、解决问题的方法、面向对象程序设计、图形用户界面设计、异常处理、I/O和递归等内容。此外,本书还全面且深入地覆盖了一些高级主题,包括算法和数据结构、多线程、网络、国际化、高级GUI等内容。 本书中文版由《Java语言程序设计:基础篇》和《Java语......一起来看看 《Java语言程序设计》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

随机密码生成器
随机密码生成器

多种字符组合密码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器