What is the idiomatic Ember 2 way to create instances of a custom class, with access to services

I have a custom class, Tile, in which I want access to a service:

export default Ember.Object.extend({
  linker: Ember.inject.service()
});

This required registering the class as a factory in an initializer:

application.register('concern:tile', Tile, { singleton: false });

I then want to be able to create several instances of this, initialized with different properties. I was hoping to do the following:

let tileFactory = Ember.getOwner(this).lookupFactory('concern:tile');
tileFactory.create(details1);
tileFactory.create(details2);

But the only way I can figure out how to use lookupFactory is like this:

let factory = Ember.getOwner(this).__container__.lookupFactory('concern:tile');
factory.create(details1);

I am under the impression that we shouldn’t use __container__.

Am I doing something gravely wrong in trying to have this concept of a concern which is a container-aware class of which I can make several instances?

I realize I can do the following:

tile = Ember.getOwner(this).lookup('concern:tile');
tile.setProperties(details1);

But this seems inefficient, but more importantly is problematic because init is called when nothing is set and then when I do setProperties the various bindings or observers update, again.

I feel there is something fundamental I’m missing.

Ember.getOwner(this)._lookupFactory(type).create(..);

Ah. I can confirm that this works. Although _lookupFactory also appears to be marked @private. It would be nice if this got a public API entrypoint.

I went through a very similar issue. _lookupFactory now seems to be resolveRegistration.

Ember.getOwner(this).resolveRegistration('some:object).create();

This solution worked in my case.

https://discuss.emberjs.com/t/best-practices-accessing-app-config-from-addon-code/7006/16

This is now the canonical way of doing factory lookups:

let factory = owner.factoryFor('widget:slow');
let klass = factory.class;
klass.hasSpeed('slow'); // true

http://emberjs.com/deprecations/v2.x/#toc_migrating-from-_lookupfactory-to-factoryfor

2 Likes