有一个使用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
我使用这里提出的解决方案之一:如何从 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;
任何人都知道是否有更好的方法可以做到这一点,或者是否有任何重要的理由不这样做?