Initializers Edit Page


Initializers provide an opportunity to configure your application as it boots.

There are two types of initializers: application initializers and application instance initializers.

Application initializers are run as your application boots, and provide the primary means to configure dependency injections in your application.

Application instance initializers are run as an application instance is loaded. They provide a way to configure the initial state of your application, as well as to set up dependency injections that are local to the application instance (e.g. A/B testing configurations).

Operations performed in initializers should be kept as lightweight as possible to minimize delays in loading your application. Although advanced techniques exist for allowing asynchrony in application initializers (i.e. deferReadiness and advanceReadiness), these techniques should generally be avoided. Any asynchronous loading conditions (e.g. user authorization) are almost always better handled in your application route's hooks, which allows for DOM interaction while waiting for conditions to resolve.

Application Initializers

Application initializers can be created with Ember CLI's initializer generator:

1
ember generate initializer shopping-cart

Let's customize the shopping-cart initializer to inject a cart property into all the routes in your application:

app/initializers/shopping-cart.js
1
2
3
4
5
6
7
8
export function initialize(application) {
  application.inject('route', 'cart', 'service:shopping-cart');
};

export default {
  name: 'shopping-cart',
  initialize: initialize
};

Application Instance Initializers

Application instance initializers can be created with Ember CLI's instance-initializer generator:

1
ember generate instance-initializer logger

Let's add some simple logging to indicate that the instance has booted:

app/instance-initializers/logger.js
1
2
3
4
5
6
7
8
9
export function initialize(applicationInstance) {
  var logger = applicationInstance.lookup('logger:main');
  logger.log('Hello from the instance initializer!');
}

export default {
  name: 'logger',
  initialize: initialize
};

Specifying Initializer Order

If you'd like to control the order in which initializers run, you can use the before and/or after options:

app/initializers/config-reader.js
1
2
3
4
5
6
7
8
9
export function initialize(application) {
  // ... your code ...
};

export default {
  name: 'configReader',
  before: 'websocketInit',
  initialize: initialize
};
app/initializers/websocket-init.js
1
2
3
4
5
6
7
8
9
export function initialize(application) {
  // ... your code ...
};

export default {
  name: 'websocketInit',
  after: 'configReader',
  initialize: initialize
};

Note that ordering only applies to initializers of the same type (i.e. application or application instance). Application initializers will always run before application instance initializers.