0

Cannot get an instance from the inversify container when I try to execute getNamed(). The container is well defined, typescript does not complain, I can see that the type of the import is "Container"; however, in the runtime container is undefined.

I'm binding UserRepo class as shown below, and exporting the container as "Registry"

container.bind<Repository>('Repository').to(UserRepo).inSingletonScope().whenTargetNamed('User');
.
.
.
export { container as Registry };
import { Registry } from '../registry';
import { UserRepo } from '../repositories/userRepository';
const userRepo: UserRepo = Registry.getNamed('Repository', 'User'); // throws an error

The error I get is

uncaughtException: Cannot read property 'getNamed' of undefined
TypeError: Cannot read property 'getNamed' of undefined

I am executing the same code, for a different class, in the root of my application, and it works. It would be great if anyone can point out where I am making a mistake.

Kaan Yalti
  • 113
  • 2
  • 9
  • Are you using `reflect-metadata`? Maybe, if you're importing that package inside of `../registry` and importing that file multiple time, this could be the problem, since `reflect-metadata` should only be imported once. – Kevin Pastor Apr 22 '19 at 20:54
  • I am using reflect-metadata. I was importing it in the registry. Tried moving it to the entry point of my application, did not help. I think the problem is because registry is not ready for some reason when I start the application. If I try to call getNamed() in a function, which gets called only when my server receives a request, everything works. So I feel like it is an async issue, but I don't know how to resolve it. – Kaan Yalti Apr 25 '19 at 13:50

0 Answers0