I'm trying to implement InversifyJS in one of my Express projects, everyting is working perfect except the websockets. The WebsocketServer requires a built server instance, and I store connections in the express object, like this:
const port = 3000;
await container.loadAsync(bindings);
const app = new InversifyExpressServer(container);
const WebSocketServer = require('ws').Server;
const server = app.build();
server.listen(port, () => {
console.log(`Server running at http://127.0.0.1:${port}/`)
});
const wss = new WebSocketServer({server: server, path: "/hereIsWS"});
wss.on("connection", function(ws){
let id = Math.random();
CLIENTS[id] = ws;
ws.on('close', function() {
delete CLIENTS[id];
server.set("clients", CLIENTS);
});
// console.log("app", app);
server.set("clients", CLIENTS);
});
Now I have a WebsocketService where I manage the messages, I used to build it with a parameter private app: express.Application
in the constructor and the connected clients are there, but I can't manage to inject the the object using inversify. Does anybody know how to inject that using inversify?.
According to the code above. You need to retrieve an object from the object locator - container. In socket events you have the access to the parent closures where the container is defined. So, retrieve any container you need in a common way
const ninja = myContainer.get<Warrior>(TYPES.Warrior);
@inject - It is a helper that retrieve a service and binds it to a property of a class(two operations) that is wrapped by decorator @injectable. You do not need it here.