Inject service on another service


#1

Suppose an app has 2 services:

  • service:log
  • service:foo

where foo wants to use log.

Suppose we want all services to be able to log and if in an initializer we did:
application.inject('service', 'log', 'service:log')
Ember throws: Error: Cannot inject a service:log on other service(s).

But we can inject log only on foo:
application.inject('service:foo', 'log', 'service:log')
which works.

This brought up some questions:

  1. From a design point of view what impact would it have to inject a service on another service? Is it better avoided?

  2. Instead of a service, we can use a log util which maybe be a plain JavaScript object holding functions say log.info() and log.error().
    Then, import it:
    import log from 'my-app/utils/log'
    and invoke it:
    log.error('An error occurred.')
    Wouldn’t this also be a solution. (btw, in this case, will log no longer be a singleton if imported in multiple files?)

Just trying to better understand this. Would be great if anyone could point out pros and cons. Thanks.


#2

You can inject a service onto a service using ad hoc injection:

// app/services/some-other-service.js
export default Ember.Service.extend({
  cart: Ember.inject.service('shopping-cart')
});

See the Ad Hoc section in the guides: https://guides.emberjs.com/v2.4.0/applications/dependency-injection/