Search code examples
ember.jsember-cli

How to do dependency injection in Ember with Ember CLI?


First, I made a small Ember app without Ember CLI.

I had this piece of code.

window.MyApp = Ember.Application.create({
  ready: function() {
    this.register('session:current', MyApp.SessionController, { singleton: true });
    this.inject('controller', 'session', 'session:current');
  }
});

This worked.

Then I decided to rewrite everything from scratch with Ember CLI.

I edited the file app/app.js and added the ready hook just like in my previous version.

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver,
  ready: function() {
    this.register('session:current', App.SessionController, { singleton: true });
    this.inject('controller', 'session', 'session:current');
  }
});

This doesn't work.

The session controller does exist. That's the content of the file app/controllers/session.js

export default Ember.Controller.extend({
  isLoggedIn: false,
});

The error message I get is

TypeError: Attempting to register an unknown factory: `session:current`

It appears in the browser.

I googled that message, but I found nothing about dependency injection in Ember CLI.

Any idea?


Solution

  • In ember-cli you can use ember generate service <name of service> and ember generate initializer <name of initializer> to build the stubs to achieve this, which is far better than fiddling about with app.js.

    You create a service basically like this:

    // app/services/notifications.js
    import Ember from 'ember';
    
    export default Ember.Object.extend({
      initNotifications: function() {
         // setup comes here
      }.on('init'),
    
      // Implementation snipped, not relevant to the answer.
    });
    

    And the initializer, which injects the service into the component(s) of your application which need it:

    // app/initializers/notifications-service.js
    import Notifications from '../services/notifications';
    
    export default {
      name: 'notification-service',
      after: 'auth-service',
    
      initialize: function( container, app ) {
        app.register( 'notifications:main', Notifications, { singleton: true } );
        app.inject( 'component:system-notifications', 'notificationService', 'service:notifications' );
        app.inject( 'service:auth', 'notificationService', 'service:notifications' );
      }
    };
    

    With that, it becomes available as notificationService on the components specified.

    Documentation on the subject of dependency injection in Ember can be found at http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/