Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Services and Dependency Injection

Dependency Injection and the Owner

Understand how Ember finds services: the registry, container and owner, lookup names, getOwner, factoryFor, and how tests replace a service with a fake.

When you write @service cart; in a component, you never write new CartService(). Something else finds, builds and hands over the object. That something is Ember's dependency injection (DI) system. You can use services happily without knowing how it works, but understanding it explains a lot: why tests can swap a service for a fake, why plain classes cannot use @service by default, and what getOwner is for.

This lesson opens the box. It names the three pieces (registry, container, owner), shows the lookup names that tie everything together, and finishes with a runnable model of the same mechanism.

Names, not classes

Ember identifies every injectable thing with a string of the form type:name:

Lookup name Comes from
service:shopping-cart app/services/shopping-cart.js
route:posts/index app/routes/posts/index.js
controller:application app/controllers/application.js
component:cart-badge app/components/cart-badge.gjs
helper:format-price app/helpers/format-price.js
template:application app/templates/application.hbs

The type comes from the folder and the name from the dasherized file path. At boot the resolver turns these file names into entries in the registry.

Registry, container, owner

  • The registry maps lookup names to classes (the "factories"). It answers "what class is service:cart?".
  • The container creates instances from the registry and caches singletons. It answers "give me the one service:cart object".
  • The owner is the object that holds the registry and the container together. In an app, the owner is the application instance. In tests it is a test-sized application instance (this.owner).

Everything that Ember creates for you (components, routes, services) is given a reference to the owner when it is built. That reference is how @service works: the decorator is shorthand for "get my owner, then owner.lookup('service:...')".

flowchart TD
  O["Owner (application instance)"] --> R["Registry: names to classes"]
  O --> C["Container: cached instances"]
  C -->|"lookup('service:cart')"| I["The single cart instance"]
  R -->|"class for service:cart"| C
  X["Component / Route / Service"] -->|"@service cart"| O

A @service property asks the owner, which asks the container, which uses the registry the first time.

Looking things up by hand

You rarely need to, but you can use the owner directly. Import getOwner and read from it:

app/utils/analytics.js

JavaScript
import { getOwner } from '@ember/owner';

export function trackPageView(context, path) {
  const owner = getOwner(context);
  const analytics = owner.lookup('service:analytics');
  analytics.pageView(path);
}

getOwner(thing) works on anything Ember created, such as a component or a service. The owner offers a few methods worth knowing:

Method What it does
owner.lookup('service:x') returns the cached singleton instance (creating it on first use)
owner.factoryFor('model:x') returns the factory so you can call .create() yourself
owner.register('service:x', Class) adds or replaces an entry in the registry (before the first lookup)
owner.resolveRegistration('service:x') returns the registered class without creating an instance

Prefer @service when you can: it is readable and keeps dependencies visible at the top of the class. Use getOwner in utility code that is not itself created by Ember.

Plain classes need an owner

A class you create with new is not known to Ember, so it has no owner and @service cannot work in it. There are two ways to fix that.

  1. Pass an owner explicitly with setOwner, then injection works:
JavaScript
import { setOwner } from '@ember/owner';
import { service } from '@ember/service';

class PriceCalculator {
  @service session;

  constructor(owner) {
    setOwner(this, owner);
  }
}

// In a component or service:
// const calc = new PriceCalculator(getOwner(this));
  1. Or let the container build it: getOwner(this).factoryFor('utility:price-calculator').create() for a registered class.

For small helpers it is often simplest to pass the services as ordinary constructor arguments instead; then your class is easy to test without any Ember at all.

Injection happens when the property is first read, not at construction. Reading an injected service inside the constructor of a plain class that has not yet been given an owner throws an error. Call setOwner first.

Why DI matters: swapping implementations

Because code asks for service:session by name, whoever controls the registry controls what comes back. That is how tests replace a real service with a fake:

tests/unit/example-test.js

JavaScript
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import Service from '@ember/service';

class FakeSession extends Service {
  isLoggedIn = true;
  userName = 'Test User';
}

module('Unit | greeting', function (hooks) {
  setupTest(hooks);

  test('it greets the signed-in user', function (assert) {
    this.owner.register('service:session', FakeSession);
    const session = this.owner.lookup('service:session');
    assert.strictEqual(session.userName, 'Test User');
  });
});

The code under test still says @service session and never knows it received a fake. Acceptance and unit tests uses this a lot.

A model of the mechanism

The stand-in below implements a small registry, container and owner, plus a service() helper that behaves like the decorator: a getter that asks the owner on first read. Then it swaps an implementation, exactly like the test above.

JS Stand-in: an owner that resolves injections

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that Greeter was not changed between the two runs. Only the registry differed. This is what makes Ember code testable: dependencies are looked up, not hard-coded.

Services that depend on services

The same mechanism lets one service inject another. The lookup is lazy, so checkout can depend on cart and cart could even use checkout without a loading-order problem: neither is created until some code reads the property.

JS Stand-in: services depending on services

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The log shows checkout built first, then cart and tax only when total() reads them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the owner hold?

    The owner (the application instance, or a test app instance) ties the registry and the container together. Lookups go through it.
  2. 2. Why can a test replace service:session with a fake without editing the component under test?

    Code depends on the lookup name, not on a concrete class. Registering another class under that name is all a test needs.
  3. 3. You write new PriceCalculator() and it has an @service property. Reading the property throws. What is missing?

    @service resolves through the owner. Objects created with new have none until you give them one with setOwner.
  4. 4. Which method returns the single cached instance of a service?

    lookup creates the instance on first use and returns the same one afterwards. resolveRegistration only returns the class.

Summary

  • Everything injectable has a lookup name like service:shopping-cart, derived from the file name.
  • The registry maps names to classes, the container caches instances, and the owner holds both.
  • @service is a lazy owner.lookup; getOwner/setOwner connect plain code to the owner.
  • Because code asks by name, tests can register a fake before the first lookup.
  • Services may inject other services; lazy creation avoids ordering problems.

Next: Built-in Services: Router and Store