In the last episode we looked at injecting a service into a component using Ember.inject.service(). We saw how this lazily injects the service, initializing the service only once it is called. Today, let's look at another way to inject a service using an initializer.

We can start with the app that we built in the last episode. For the most part when we are dealing with a current-user or session data, we probably will need to make it available in several places in our application. Let's use an initializer and inject our service into our controllers, models, and routes. To do this we can generate an initializer from the root of our application.

ember g initializer session

Now, we can modify the initializer to inject our service anywhere we want in our application. In app/services/session.js:

export function initialize(application) {
  application.inject('route', 'user', 'service:currentUser');
  application.inject('controller', 'user', 'service:currentUser');
  application.inject('model', 'user', 'service:currentUser');
}

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

Now, all routes, controllers, and models will be instantiated with the service current-user injected as the property user. Since it is available in our controllers we can access our service's userInfo.firstName property from a template by using {{user.userInfo.firstName}}. One other consequence of using an initializer to inject our service is that it is no longer lazily loaded but is loaded as soon as the routes, controllers, and models are created.

If we remove the component that is calling s the service from our application template we will see that now our service's init function is now still being called even though the service isn't being called anywhere in the application. Another related consequence is that from our route, controller, or model's JavaScript files we need not call this.get('current-user.userInfo.firstName'); we can now call this.user...;.

As I mentioned before, you should be conscious not to overuse services, especially those injected with initializers. They can quickly start to feel like globals and can be abused. Tomorrow we will look modifying data in a service.

Josh Adams

I've been building web-based software for businesses for over 18 years. In the last four years I realized that functional programming was in fact amazing, and have been pretty eager since then to help people build software better.

  1. Comments for Dependency Injection with an Initializer

You must login to comment

You May Also Like