1 year ago

#75967

test-img

Guerric P

How to implement a class dependency injection based on the parameter types?

I have answered a question here about how to implement dependency injection with TypeScript's parameter decorators: Get class constructor argument names

Basically the solution looks like this:

const metadataMap = new Map();

interface Constructable {
    new(...args: any[]): any;
}

function Inject(value: any) {
    return function (target: Constructable, key: PropertyKey, paramIndex: number) {
        metadataMap.set(target, Object.assign(metadataMap.get(target) || [], { [paramIndex]: value }));
    }
}

class Test {
    greetings: string;
    name: string;

    constructor(@Inject('Hello there!') greetings: string, @Inject('Guerric') name: string) {
        this.greetings = greetings;
        this.name = name;
    }

    sayHello() {
        console.log(`${this.greetings} My name is ${this.name}`);
    }
}

function factory<T extends Constructable>(clazz: T): InstanceType<T> {
    return new clazz(...metadataMap.get(clazz));
}

factory(Test).sayHello();

I am trying to go further and implement dependency injection based on Angular's system that does not necessarily rely on annotations but on the parameter types.

I have no idea where to start because I'd have to associate values (classes and instances of classes) from TypeScript types which (as far as I know) is not possible.

Does Angular use some kind of black magic in their build process, or am I missing something in TypeScript?

angular

typescript

dependency-injection

0 Answers

Your Answer

Accepted video resources