【问题标题】:Best way to inject a function using InversifyJS使用 InversifyJS 注入函数的最佳方法
【发布时间】:2017-10-10 17:41:05
【问题描述】:

有一个official recipe 可以使用InversifyJS 注入函数。基本上,我们定义了一个帮助函数,它将返回给定函数 func 的柯里化版本,其所有依赖项都使用 container.get(...) 解析:

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 };

我们这样使用它:

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 };

我想自动注入函数,而不是显式地提供它对bindDependencies 的依赖关系,可能基于函数的参数名称。像这样的:

import { default as express, Router } from 'express';

import { bindDependencies } from '../injector/injector.utils';

import { AuthenticationMiddleware } from './authentication/authentication.middleware';
import { UsersMiddleware } from './users/users.middleware';

import { ENDPOINTS } from '../../../../common/endpoints/endpoints.constants';


function getRouter(
    authenticationMiddleware: AuthenticationMiddleware,
    usersMiddleware: UsersMiddleware,
): express.Router {
    const router: express.Router = Router();

    const requireAnonymity: express.Handler = authenticationMiddleware.requireAnonymity.bind(authenticationMiddleware);
    const requireAuthentication: express.Handler = authenticationMiddleware.requireAuthentication.bind(authenticationMiddleware);

    router.route(ENDPOINTS.AUTHENTICATION)
        .put(requireAnonymity, authenticationMiddleware.login.bind(authenticationMiddleware))
        .delete(requireAuthentication, authenticationMiddleware.logout.bind(authenticationMiddleware));

    router.route(ENDPOINTS.USER)
        .put(requireAnonymity, usersMiddleware.register.bind(usersMiddleware))
        .post(requireAuthentication, usersMiddleware.update.bind(usersMiddleware))
        .delete(requireAuthentication, usersMiddleware.remove.bind(usersMiddleware));

    return router;
}

const router: express.Router = invoke(getRouter);

export { router as Router };

请注意,在这种情况下,我只想调用一次注入的函数并获取它的返回值,这就是我要导出的值,所以也许有更好的方法可以做到这一点,而无需将代码包装在函数中,但我虽然直接在我的组合根之外使用container.get(...) 不是一个好主意,因为此模块的依赖关系将不清楚,并且可能分布在其所有行中。此外,导出该函数将简化测试。

回到我的问题,我的invoke 函数如下所示:

function invoke<T>(fn: Function): T {
    const paramNames: string[] = getParamNames(fn);

    return fn.apply(null, paramNames.map((paramName: string)
        => container.get( (<any>container).map[paramName.toUpperCase()] ))) as T;
}

对于getParamNames,我使用这里提出的解决方案之一:How to get function parameter names/values dynamically from javascript

(&lt;any&gt;container).map 是我在创建容器后在inversify.config.ts 中创建的一个对象,它链接了我所有依赖项的键和真实键的字符串表示形式,无论其类型如何(在这种情况下,只是symbolFunction):

const container: Container = new Container();

container.bind<FooClass>(FooClass).toSelf();

...

const map: ObjectOf<any> = {};

(<any>container)._bindingDictionary._map
    .forEach((value: any, key: Function | symbol) => {
        map[(typeof key === 'symbol'
            ? Symbol.keyFor(key) : key.name).toUpperCase()] = key;
    });

(<any>container).map = map;

有人知道是否有更好的方法可以做到这一点,或者是否有任何重要的理由不这样做?

【问题讨论】:

  • @ower-reloaded 也许您可以对此有所了解?

标签: javascript node.js typescript dependency-injection inversifyjs


【解决方案1】:

使用函数参数名称的主要问题是压缩代码时的潜在问题:

function test(foo, bar) {
    console.log(foo, bar);
}

变成:

function test(a,b){console.log(a,b)}

因为您正在使用 Node.js 应用程序,您可能没有使用压缩,所以这对您来说应该不是问题

我认为您的解决方案是一个很好的临时解决方案。如果你检查TypeScript Roapmap,在“未来”部分我们可以看到:

  • 函数表达式/箭头函数的装饰器

这意味着将来 InversifyJS 将允许您执行以下操作:

注意:假设AuthenticationMiddlewareUsersMiddleware

@injectable()
function getRouter(
    authenticationMiddleware: AuthenticationMiddleware,
    usersMiddleware: UsersMiddleware,
): express.Router {
    const router: express.Router = Router();

    const requireAnonymity: express.Handler = authenticationMiddleware.requireAnonymity.bind(authenticationMiddleware);
    const requireAuthentication: express.Handler = authenticationMiddleware.requireAuthentication.bind(authenticationMiddleware);

    router.route(ENDPOINTS.AUTHENTICATION)
        .put(requireAnonymity, authenticationMiddleware.login.bind(authenticationMiddleware))
        .delete(requireAuthentication, authenticationMiddleware.logout.bind(authenticationMiddleware));

    router.route(ENDPOINTS.USER)
        .put(requireAnonymity, usersMiddleware.register.bind(usersMiddleware))
        .post(requireAuthentication, usersMiddleware.update.bind(usersMiddleware))
        .delete(requireAuthentication, usersMiddleware.remove.bind(usersMiddleware));

    return router;
}

或以下:

注意:假设AuthenticationMiddlewareUsersMiddleware接口

@injectable()
function getRouter(
    @inject("AuthenticationMiddleware") authenticationMiddleware: AuthenticationMiddleware,
    @inject("UsersMiddleware") usersMiddleware: UsersMiddleware,
): express.Router {
    const router: express.Router = Router();

    const requireAnonymity: express.Handler = authenticationMiddleware.requireAnonymity.bind(authenticationMiddleware);
    const requireAuthentication: express.Handler = authenticationMiddleware.requireAuthentication.bind(authenticationMiddleware);

    router.route(ENDPOINTS.AUTHENTICATION)
        .put(requireAnonymity, authenticationMiddleware.login.bind(authenticationMiddleware))
        .delete(requireAuthentication, authenticationMiddleware.logout.bind(authenticationMiddleware));

    router.route(ENDPOINTS.USER)
        .put(requireAnonymity, usersMiddleware.register.bind(usersMiddleware))
        .post(requireAuthentication, usersMiddleware.update.bind(usersMiddleware))
        .delete(requireAuthentication, usersMiddleware.remove.bind(usersMiddleware));

    return router;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 2021-01-04
    • 2012-11-12
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多