Support for injecting dependencies into functions
I really love Inversify. But I can not find any support for injecting dependencies into functions. This seems an obvious thing to support in Javascript. Quite often we only need functions rather than classes. I would like to be able to inject dependencies into functions. For example a Route function for configuring a router in express which requires a controller as a dependency.
Do you provide support for this, and if not do you have any plans to support it?
I managed to get this working from the recipe in here https://github.com/inversify/InversifyJS/blob/master/wiki/recipes.md
Is this the correct way to do it?
Hi @JonathanYates, sorry for the late reply. The recipe that you found is the recommended way. Inversify is heavily driven by metadata and at the moment decorators can only be applied to classes. In the future, they may be applied to functions and we will revisit how injecting into functions might work.
@remojansen
Hello, I came across this and am wondering if this solution is also valid with typescript? I have been trying to get it to work and find there are type errors because I call my function without the injected dependencies and typescript expects me to pass the dependency which was bound already.
@TomzBench Were you able to discover a mechanism to use injection in functions finally with TypeScript?
@benze yes, the thing that I missed is capturing the return from bind. you do something like this:
import { container } from "./inversify.config"
function bindDependencies(func, dependencies) {
let injections = dependencies.map((dependency) => {
return container.get(dependency);
});
return func.bind(func, ...injections); // <--- make sure to capture this return value
}
function foo(){ /* ... */}
const fooWithInjections = bindDependencies(foo, dependencies):
foo(/* bad */);
fooWithInjections(/* good */);
How to type func, dependencies of bindDependencies(func, dependencies) in typescript? Have some issues with this, mainly with second argument.