LoginSignup
5
6

More than 5 years have passed since last update.

TypeScriptで簡単なDI

Last updated at Posted at 2018-07-15

はじめに

シンプルにDIがやりたかった。

DIコンテナつくる

Dependencies.ts
type Class<T> = new() => T

export default class Dependencies {

    static container: Map<Class<any>, any> = new Map()

    static inject<T>(clazz: Class<T>): T {
        const instance = Dependencies.container.get(clazz)
        if (instance) {
            return instance
        }
        const newInstance = new clazz()
        Dependencies.container.set(clazz, newInstance)
        return newInstance
    }
}

使う

import Dependencies from "./Dependencies";

class Test {} // Singletonにしたいクラス

const val1 = Dependencies.inject(Test)
const val2 = Dependencies.inject(Test)
console.log(val1 === val2) // true
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6