This feature especially useful if you want to store (and inject later on) some settings or configuration options. For example:
var Container =require('typedi').Container;// somewhere in your global app parametersContainer.set('authorization-token','RVT9rVjSVN');classUserRepository {constructor(container) {this.authorizationToken =container.get('authorization-token'); }}
When you write tests you can easily provide your own "fake" dependencies to classes you are testing using set method:
Container.set(CoffeeMaker,newFakeCoffeeMaker());// or for named servicesContainer.set([ { id:'bean.factory', value:newFakeBeanFactory() }, { id:'sugar.factory', value:newFakeSugarFactory() }, { id:'water.factory', value:newFakeWaterFactory() },]);
TypeDI also supports a function dependency injection. Here is how it looks like:
var Service =require('typedi').Service;var Container =require('typedi').Container;var PostRepository =Service(() => ({getName() {return'hello from post repository'; },}));var PostManager =Service(() => ({getId() {return'some post id'; },}));classPostQueryBuilder {build() {return'SUPER * QUERY'; }}var PostController =Service([PostManager, PostRepository, PostQueryBuilder], (manager, repository, queryBuilder) => {return { id:manager.getId(), name:repository.getName(), query:queryBuilder.build(), };});var postController =Container.get(PostController);console.log(postController);