InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

Ability to inject dependencies for dynamicValue from same scope

Open thynson opened this issue 6 years ago • 2 comments

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

  1. Allow inject depedencies into factory function, like nestjs does.
container.bind('Logger').toDynamicValue({ inject: ['ContextID'], factory: (ctx)=> newLogger(ctx, ...)});
  1. Make context itself be able resolve dependencies, in its own scope.
container.bind('Logger')
  .toDynamicValue((context)=> return new Logger(context.resolve('ContextID'), ...))
  .inRequestScope();

thynson avatar Sep 02 '19 14:09 thynson

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

talha5389 avatar Dec 02 '20 21:12 talha5389

Oh god this hurts so bad. :(

dustinlacewell avatar Nov 07 '21 00:11 dustinlacewell