Auto instantiating classes at app launch

I have some singleton classes that need to be instantiated when my Aurelia app first launches because they do periodic work in the background. Right now, I’m injecting them into my app.js view-model. That just doesn’t seem to be the best way to handle this pattern. Is there a better way to do this?

You can instantiate it using an aurelia.container in the configure function. But I would just inject it into the root view. Why do you consider this not the best way?

You can do it in aurelia app bootstrap code in main.js

export function configure(aurelia) {
  /* ... */
  const yourInstance = new YourInstance();
  // use this instance for all injections of class YourInstance.
  aurelia.container.registerInstance(YourInstance, yourInstance);

Personally I prefer aurelia.container.registerInstance('YourInstance', yourInstance);, so in my components, I don’t have to import YourInstance explicitly, just use string to inject @inject('YourInstance').

I register lots of my injections after String names using registerInstance, registerSingleton and registerTransient, so my components js file is totally decoupled with all other class definitions.

I am getting an error:

TypeError: Promise.config is not a function. (In ‘Promise.config({
longStackTraces: _environment2.default.debug,
warnings: {
wForgottenReturn: false
})’, ‘Promise.config’ is undefined)


import {MyClass} from 'my-class';
import environment from './environment';

//Configure Bluebird Promises.
  longStackTraces: environment.debug,
  warnings: {
    wForgottenReturn: false

export function configure(aurelia) {

  const myClass = new MyClass();
  aurelia.container.registerSingleton('MyClass', myClass);

  aurelia.start().then(() => aurelia.setRoot());

If I remove the new code (importing of MyClass and it’s references), the error no longer occurs.

Promise.config is a bluebird method. It sounds like your class somehow prevented bluebird to replace global window.Promise variable.

You are using wrong method. Not registerSingleton, use registerInstance, as you feed an instance to DI. Try again pls.

If you want to use registerSingleton, registerSingleton('MyClass', MyClass), but that will delay the instance creation to first encounter of injection.

This works fine. Thank you for your help!

This was asked before: Causing Aurelia to create singletons before VM's need them.