Initializing a WebSocket connection before application start

Is there an equivalent to calling activate() on the root component?

I need to initialize a WebSocket connection before my application loads. If I were doing this on a per-route basis, I would just make sure that the connection exists in the activate() method of the component I’m routing to before allowing it to render. However, in this case I need that same type of functionality at the root application level.

Since there’s no asynchronous hook/life-cycle method that I’m aware of that can be called on the root application component, I’m assuming that this could only be done in main.js/ts (i.e. ensuring that the connection is open before calling setRoot and starting the application). But if I were to do it this way, how would I then pass a reference to my “new WebSocket()” into my application? Would I have to do something ugly like attach it to the window object/global scope? I’d rather use dependency injection if possible, but that’s only available after the application has started, correct?

2 Likes

you can register an instance in the container in the configure method in main, then @inject(WebSocket) in components.

const socket = new WebSocket(url);
aurelia.container.registerInstance(WebSocket, socket);
2 Likes

I think that’s exactly what I was looking for, thank you!

1 Like