nicojs / typed-inject

Type safe dependency injection for TypeScript
Apache License 2.0
448 stars 23 forks source link

Get the token of the target #33

Open mahulst opened 3 years ago

mahulst commented 3 years ago

Very cool library, type safety is especially nice!

We currently use inversify, and in toDynamicValue you get Context as an argument. In the context you can look up the token of the target where the current value is injected into. We use that for logging purposes.

With the magic token TARGET_TOKEN I am able to get the name of the constructor that requested this value. But I also would like the token, as we can give some more context in the token than the class name.

Is there way this is currently possible?

Minimal example:

function TestFactory (target: Function | undefined) {  
    // Here I would like to get access to the token of the target.
    console.log(target) // [Function: MagicTokenTest] { inject: [ 'TestFactory' ] }
    return 'hello, world!'
}
TestFactory.inject = [TARGET_TOKEN] as const

class MagicTokenTest {
    public static inject = ['TestFactory'] as const
    constructor(testFactory: string) {}
}

const appInjector = createInjector()
    .provideFactory('TestFactory', TestFactory, Scope.Transient)
    .provideClass('token.i.use.for.logging', MagicTokenTest);

appInjector.resolve('token.i.use.for.logging');
nicojs commented 2 years ago

Hi @mahulst thanks for the kind words and sorry for the late reply.

Sounds like a fair proposal. I'm open to PRs.