【发布时间】: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
(<any>container).map 是我在创建容器后在inversify.config.ts 中创建的一个对象,它链接了我所有依赖项的键和真实键的字符串表示形式,无论其类型如何(在这种情况下,只是symbol或Function):
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