Reputation: 542
I'm facing this kind of problem: I'm creating Event Manager with ability to handle several concrete providers, and I'm struggling with dependency injection issue here.
I'm using:
[email protected]
, [email protected]
, [email protected]
, [email protected]
Lets see that in code:
const socketIO: SocketIO.Server = io.listen(instance);
kernel.bind<SocketIO.Server>(TYPES.SocketIO).toConstantValue(socketIO);
const eventManager: IEventManager = kernel.get<IEventManager>(TYPES.IEventManager);
eventManager.init(kernel.getAll<IEventManagerProvider>(TYPES.IEventManagerProvider));
console.log(eventManager);
And console logs me that event manager is undefined
, which crashes the whole app. But...
When I disable the kernel.getAll(...)
from init, then I'm receiving just what I've expected:
const eventManager: IEventManager = kernel.get<IEventManager>(TYPES.IEventManager);
eventManager.init([]);
console.log(eventManager);
Gives me: MultipleProvidersEventManager { providers: {} }
. The init method is very simple by itself and contains:
@provideSingleton(TYPES.IEventManager)
class MultipleProvidersEventManager {
...
public init(providers: IEventManagerProvider[]): void {
forEach(providers, this.registerProvider);
}
public registerProvider(provider: IEventManagerProvider): void {
if (this.providers[provider.type()]) {
throw new Error('Event Manager provider already registered');
}
console.log('Registered ' + provider.type() + ' event manager provider');
this.providers[provider.type()] = provider;
}
...
}
So my problem is that I have to wait with calling the init method until all required objects are stored properly in InversifyJS container and can be returned. But I don't know how :(. Can someone explain me how should I solve this problem ?
Upvotes: 1
Views: 1183
Reputation: 542
Ok, I've solve it.
The problem was in totally different place that I was thinking on the beginning.
So... in MultipleProvidersEventManager
class on init
method, forEach
was loosing the context of the caller. Adding bind
soved the problem..
forEach(providers, this.registerProvider.bind(this));
... is the anwser.
Upvotes: 1