Skip to content

Support injection of dynamic values #181

Description

@remojansen

Expected Behavior

We need a way to support bindings for dynamic values via a new operator toDynamicValue:

interface IUseDate {
    doSomething();
}

@injectable()
class UseDate implements IUseDate {
    constructor(@inject("Date") private currentDate: Date) {
    }

    doSomething() {
        console.log(`Today is ${this.currentDate}`);
    }
}

let kernel = new Kernel();
kernel.bind<IUseDate>("IUseDate").to(UseDate);
kernel.bind<Date>("Date").toDynamicValue(() => { new Date(); });

let subject = kernel.get<IUseDate>("IUseDate");
subject.doSomething(); // will print a new date in each instance

Current Behavior

We only support bindings for constant values via toValue:

interface IUseDate {
    doSomething();
}

@injectable()
class UseDate implements IUseDate {
    constructor(@inject("Date") private currentDate: Date) {
    }

    doSomething() {
        console.log(`Today is ${this.currentDate}`);
    }
}

let kernel = new Kernel();
kernel.bind<IUseDate>("IUseDate").to(UseDate);
kernel.bind<Date>("Date").toValue(new Date());

let subject = kernel.get<IUseDate>("IUseDate");
subject.doSomething(); // will print the same date over and over

Context

This use case comes from #177.

It might be a good idea to rename the current `toValue:

kernel.bind<IWeapon>("IWeapon").toValue(new Engine());
kernel.bind<IWeapon>("IWeapon").toDynamicValue(() => { return new Engine(); });

The new named used would be toConstantValue:

kernel.bind<IWeapon>("IWeapon").toConstantValue(new Engine());
kernel.bind<IWeapon>("IWeapon").toDynamicValue(() => { return new Engine(); });

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions