问题
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