InversifyJS
InversifyJS copied to clipboard
Ability to inject dependencies for dynamicValue from same scope
Make toDynamicValue binding able to injects its dependencies, to ensure its dependencies are resolved in same scope.
Motivation
I'm trying to implements a context logger.
container.bind('ContextID')
.toDynamicValue(()=> uuid())
.inRequestScope();
container.bind('Logger')
.toDynamicValue((context)=> {
const targetName = (context.currentRequest.parentRequest.serviceIdentifier as Function).name;
return new Logger(
context.container.get('ContextID'),
targetName
)
})
.inTransientScope();
class FooComponent {
@inject('Logger')
loggerA: Logger;
}
class BarComponent {
@inject('Logger')
loggerB: Logger;
}
loggerA and loggerB cannot have same context id, even if they are resolved in same request, because context.container.get('ContextID') create a new request scope.
Possible Solution
- Allow inject depedencies into factory function, like nestjs does.
container.bind('Logger').toDynamicValue({ inject: ['ContextID'], factory: (ctx)=> newLogger(ctx, ...)});
- Make context itself be able resolve dependencies, in its own scope.
container.bind('Logger')
.toDynamicValue((context)=> return new Logger(context.resolve('ContextID'), ...))
.inRequestScope();
I also need this functionality. Right now, there does not seem to be a way to get a dependency already resolved in request scope in toFactory, toDynamicValue etc without resetting/recreating resolved object in request scope
Oh god this hurts so bad. :(