Using needs to inject objects into other objects

I wanted to understand if the needs attribute could be used to inject arbitrary objects into controllers, routes and views.

I am developing an Ember.js application where I am writing a custom data-service layer that communicates with the backend to load and persist data. I define Ember Objects which represent the various backend services such as:

App.SessionServiceClient = Em.Object.extend({
  // methods and attributes
});

App.UserServiceClient = Em.Object.extend({
  // methods and attributes
});

I now register these objects with the application’s container to make them available for DI:

App.register('service:session', App.SessionServiceClient, {singleton: false});
App.register('service:user', App.UserServiceClient, {singleton: false});

Now that the objects are available for injection, and if I have a controller that needs only the SessionServiceClient, can I do the following:

App.SignInController = Em.ObjectController.extend({
  needs: ['service:user'],                  // using the needs to declare dependency
  actions: {
    // actions for the view
  }
});

When i tried this, it did not work. Is this possible with Ember.js or am I doing it wrong?

inject is your friend - see http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/#toc_dependency-injection-with-code-register-inject-code - you can inject your registered service into all controllers or an individual controller in an initializer (see link for details). AFAIK needs only works with other controllers.

HTH

/Eoin/

1 Like