di.js icon indicating copy to clipboard operation
di.js copied to clipboard

Non-module constructor parameter

Open djindjic opened this issue 11 years ago • 1 comments

Is possible (and is it relevant question for this repo issues) to have some additional constructor parameter which is not injected module itself? For example coffee_type:

import {Inject} from 'di';
import {Pump} from './pump';

@Inject(Pump)
export class CoffeeMaker {
  constructor(pump, coffee_type) {
    this.pump = pump;
    this.coffee_type = coffee_type;
  }
}

let injector = new Injector();
let coffee_maker = injector.get(CoffeeMaker>>>>>('cappuccino')<<<<<<);

djindjic avatar Dec 18 '14 16:12 djindjic

Though this feature is possible and convenient, the workaround (and possibly better solution) is to supply these extra parameters through provided dependencies. For example:

import {Inject, Provide} from 'di';
import {Pump} from './pump';

class CoffeeType {}

@Inject(Pump, CoffeeType)
export class CoffeeMaker {
  constructor(pump, coffeeType) {
    this.pump = pump;
    this.coffeeType = coffeeType;
  }
}

@Provide(CoffeeType)
function Cappuccino() {
  return 'cappuccino';
}

let injector = new Injector();

let withCappucino = injector.createChild([Cappuccino]);
let coffeeMaker = withCappucino.get(CoffeeMaker);

L8D avatar May 18 '15 21:05 L8D