InfersifyJS - how to conditionally load constantValue

一世执手 提交于 2019-12-25 01:12:36

问题


I am using inversifyJS in my typescript + NODE.js application. I have for different environments different configurations:

Configuration production

const CONFIG_PRODUCTION: Object = {
    PATH_TO_STATIC_FILES: '../web/build',
    SECURE_COOKIE: false
};

export default CONFIG_PRODUCTION;

Configuration development

const CONFIG_DEVELOPMENT: Object = {
    PATH_TO_STATIC_FILES: 'build/web/build',
    SECURE_COOKIE: true
};

export default CONFIG_DEVELOPMENT;

Now on my infersify container configuration my setup looks like this:

Inversify configuration

const dependencyContainer = new Container();
dependencyContainer.bind(TYPES.ENVIRONMENTAL_CONFIG).toDynamicValue(
    (context: interfaces.Context) => context ? CONFIG_PRODUCTION : CONFIG_DEVELOPMENT);
...

export default dependencyContainer;

Now where can I decide how to load the needed config object? In my class I currently inject the property like this:

Express file

constructor(
    @inject(TYPES.ENVIRONMENTAL_CONFIG) private config: Object
) {
    ...
    console.log(config) // prints development config
}

Does inversify provide something like a setContext() function?


回答1:


I came up with to solution to bind the property with the toFactory method on the dependency container:

dependencyContainer.bind(TYPES.ENVIRONMENTAL_CONFIG).toFactory(
    () => (context: interfaces.Context) => context ? CONFIG_PRODUCTION : CONFIG_DEVELOPMENT);

after that I inject the Factory as Function in my used class:

constructor(@inject(TYPES.ENVIRONMENTAL_CONFIG) private environmentFactory: Function) {
    this.environmentalProps = this.environmentFactory(isProduction);
  }


来源:https://stackoverflow.com/questions/59344789/infersifyjs-how-to-conditionally-load-constantvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!