InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

Support for injecting dependencies into functions

Open JonathanYates opened this issue 9 years ago • 6 comments

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?

JonathanYates avatar Jan 25 '17 11:01 JonathanYates

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?

JonathanYates avatar Jan 25 '17 16:01 JonathanYates

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 avatar Jan 28 '17 23:01 remojansen

@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 avatar Apr 06 '20 22:04 TomzBench

@TomzBench Were you able to discover a mechanism to use injection in functions finally with TypeScript?

benze avatar Oct 15 '20 15:10 benze

@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 */);

TomzBench avatar Oct 21 '20 11:10 TomzBench

How to type func, dependencies of bindDependencies(func, dependencies) in typescript? Have some issues with this, mainly with second argument.

ladislavrolnik avatar Mar 25 '22 11:03 ladislavrolnik