Causing Aurelia to create singletons before VM's need them


We have a fairly complex application and would like to have a set of services that are ALWAYS created into the Aurelia context, prior to those services being injected into any VM’s.

We thought that one way to do this would be to inject a service into app.js that depends on all the services we want to spin up “early”.

Is that an expected way to do what we want, or is there another approach that is considered more “normal”?

Auto instantiating classes at app launch

You could register them directly on the Container:

Container.instance.registerInstance(MyClass, new MyClass('something'));

Or see the other options:


I tried the following. The code runs without complaining (when I finally figured out what it seems to want), but the services still do not start until a VM injects them.

container.autoRegisterAll(["SyncService", "PaymentService", "SelectedPlanService", "ProposedPlanService"])


This doesn’t actually create an instance of your service but lets the Container retrieve the best strategy for future injections. Have you tried registerInstance()? It should do what you’re looking for.


The only issue with registerInstance() is that I have to actually create the service first, which means I have to create all of its dependencies, which is what the DI engine is supposed to do without me. What I am hoping to find is a way to say “create these singletons when the app is loaded”. I suppose making a “RequiredContextService” that is injected into app.js that injects all the required dependencies would work well enough.

Thanks for your help. :slight_smile:


How about this in main.js, before the call to aurelia.setRoot:

import { SyncService } from './sync-service';
// ...
// create an instance of SyncService (and it's dependencies)
const mySyncService = aurelia.container.get(SyncService);
// return the instance created above each time SyncService is requested
aurelia.container.registerInstance(SyncService, mySyncService);


@gheoan No need to re-register them. Just call aurelia.container.get(...) for each service during the main’s configure method and that should do the trick.


That’s what I needed. It’s working great. What we’re going to end up with is sort of a “default container” of services so that they can respond to events and be loading from the server before a VM needs that data.

Thanks for the help.