LoginSignup
1
1

More than 5 years have passed since last update.

InversifyJSで関数に依存性を注入する

Posted at

背景

私用メモ。公式のWikiにあったので。

やっていく

途中までは普通にClassに注入するときと同じようにTYPESとコンテナを作る

let TYPES: {
    something: "something",
    somethingElse: "somethingElse"
};

export { TYPES };
let inversify = require("inversify");
import { TYPES } from "./constants/types";

// declare your container
let container = new inversify.Container();
container.bind(TYPES.something).toConstantValue(1);
container.bind(TYPES.somethingElse).toConstantValue(2);

export { container };

こんなようなbindDepindenciesヘルパ関数を定義する。

import { container } from "./inversify.config"

function bindDependencies(func, dependencies) {
    let injections = dependencies.map((dependency) => {
        return container.get(dependency);
    });
    return func.bind(func, ...injections);
}

export { bindDependencies };

注入先の関数を定義し、さっきのbindDepondenciesの第一引数に関数を、第二引数にTYPESを渡す。

import { bindDependencies } from "./utils/bindDependencies";
import { TYPES } from "./constants/types";

function testFunc(something, somethingElse) {
  console.log(`Injected! ${something}`);
  console.log(`Injected! ${somethingElse}`);
}

testFunc = bindDependencies(testFunc, [TYPES.something, TYPES.somethingElse]);

export { testFunc };

使う。

import { testFunc } from "./x/test_func";

testFunc();

// > Injected! 1
// > Injected! 2
1
1
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
1
1