Reach Into the Container When You Must
Owner and getOwner
The getOwner function returns the application instance and lets you do advanced container lookups for factories or late-bound services.
What you'll learn
- Import getOwner from the ember/owner package
- Use owner.factoryFor and owner.lookup
- Avoid when the service decorator is enough
Most of the time, @service is all the DI you need. But sometimes — addons,
plugin systems, dynamic class instantiation — you need the underlying
container directly. That’s what getOwner is for.
getOwner
import { getOwner } from '@ember/owner';
export default class Plugin {
constructor(host) {
this.owner = getOwner(host);
}
loadService(name) {
return this.owner.lookup(`service:${name}`);
}
} The owner is the application instance. From it, you can:
lookup(fullName)— get a singleton (e.g.'service:auth','controller:index')factoryFor(fullName)— get a factory you can instantiate manuallyregister(fullName, factory)— register a class under a name (mostly used in tests)
factoryFor
const Factory = this.owner.factoryFor('plugin:metrics');
const instance = Factory.create({ option: true }); Unlike lookup, factoryFor lets you create multiple distinct instances of
a non-singleton class. The class’s owner is set automatically, so it can
inject services.
When You Really Need It
Common cases:
- Building a plugin loader that instantiates user-supplied classes.
- Looking up a service whose name is computed at runtime.
- Inside utility functions that aren’t classes (pass
ownerexplicitly).
For everything else, @service auth is shorter and clearer.
setOwner For Plain Objects
If you build a plain object that needs DI, attach an owner manually:
import { setOwner } from '@ember/owner';
const helper = {};
setOwner(helper, this.owner); Now getOwner(helper) works inside helper methods, so you can lookup from
non-class code.
Rule Of Thumb
If a class uses @service, you’ll almost never reach for getOwner. Save it
for the few places where dynamism is unavoidable — and prefer a small
abstraction over scattering lookup calls.