Dynamically inject different object/token into a class

  Kiến thức lập trình

I need to implement some sort of strategy pattern with tsyringe but can’t figure out how to dynamically inject the strategy into my context class without polluting the dependency container.

interface IThing {
  exec(): void;
}

@injectable()
class Thing1 implements IThing {
  exec(): void {
    console.log('thing 1');
  }
}

@injectable()
class Thing2 implements IThing {
  exec(): void {
    console.log('thing 2');
  }
}

@injectable()
class Test {
  constructor(
    // how would the container know which is which between Thing1 and Thing2?
    @inject('??')
    private readonly thing: IThing,
  ) {
    thing.exec();
  }
}

// find a way to resolve `Test` and give it Thing1 or Thing2

I’m unsure how I could use container.resolve(Test) and give it Thing1/Thing2.

I know I could do something like the following, but I not sure this is very elegant, as it pollutes the container and risks instantiating Test with the wrong strategy:

@injectable()
class Test {
  constructor(
    @inject('Thing')
    private readonly thing: IThing,
  ) {
    thing.exec();
  }
}

container.provide("Thing", { useClass: Thing1/2 })
const test = container.resolve(Test) // test with proper strategy, but now the container is polluted

Is there a more elegant way to implement this pattern?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT