2

I am building a library in TypeScript that is using a dependency injection system (inversifyJS) to construct itself and resolve dependencies internally. The problem I have is - I want to expose multiple instances from the injection system to the consumers of the library.

Currently what I am trying to do is:

import kernel from "./src/inversify.config";
import EntityManager from './src/manager/entityManager.service';
import StorageService from './src/storage/storage.service';
import LanguageService from './src/language/language.service';

export { kernel.get<EntityManager>(EntityManager) as EntityManagerInstance };
export { kernel.get<EntityManager>(LanguageService) as LanguageServiceInstance };
export { kernel.get<EntityManager>(StorageService) as StorageServiceInstance };

A solution that I see is possible is to use a facade to export types and access them later:

import EntityManager from './src/manager/entityManager.service';
import StorageService from './src/storage/storage.service';
import LanguageService from './src/language/language.service';
import InjectionFacade from './utils/injection.facede';

export { EntityManager, LanguageService, StorageService, InjectiorFacade }; 
// Usage: 
// import {InjectionFacade, StorageService} from 'entity-manager';
// let injectionFacade: InjectionFacade = InjectionFacade.createAndResolve();
// let storageService: StorageService = injectionFacade.getStorageService();

But the problem with this is I have one more useless abstraction

Is there a way to implement this kind of solution without loosing type definitions and exporting ready-to-use objects?

Community
  • 1
  • 1
Deniss B.
  • 281
  • 4
  • 13

1 Answers1

4

You'd want to use a multiple-declaration variable, e.g.

export const
    EntityManagerInstance = kernel.get<EntityManager>(EntityManager),
    LanguageServiceInstance = kernel.get<EntityManager>(LanguageService),
    StorageServiceInstance = kernel.get<EntityManager>(StorageService);
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Thanks - this is what I want (for better or worse) – Deniss B. Oct 13 '16 at 07:07
  • A side note: Calling `kernel.get` many times is an indicator of a possible [anti-pattern](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/) `kernel.get` should only be used once at your [composition root](http://blog.ploeh.dk/2011/07/28/CompositionRoot/) – Remo H. Jansen Oct 13 '16 at 11:22