简体   繁体   中英

How can I export multiple object instances in TypeScript?

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?

You'd want to use a multiple-declaration variable, eg

export const
    EntityManagerInstance = kernel.get<EntityManager>(EntityManager),
    LanguageServiceInstance = kernel.get<EntityManager>(LanguageService),
    StorageServiceInstance = kernel.get<EntityManager>(StorageService);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM