Dependency injection works fine for routes and controllers, but I am having difficulty getting it to work with custom classes. Instances of route and controller classes are automatically instantiated by Ember, which may be where the problem lies. The example below should illustrate the problem. I try to inject a session singleton in routes, controllers, and a custom model class, which extends Ember.Object
. Everything works fine for routes and controllers, but it doesn't work for the custom model class.
Could the problem be that the user
is created using App.User.create
and is it therefore not managed by the application's container? In the console, I created an instance of App.IndexRoute
and the instance did not have the session injected either. What am I overlooking here?
To be clear, I have looked at other register/inject examples (even those in Ember's source code), but it seems that I am missing a key aspect of dependency injection in Ember.
Update The example below is merely an example to illustrate the problem as one wouldn't want to inject as session singleton into every user model. The real question is how to inject a singleton object into an instance if that instance isn't created by the application's container.
App = Ember.Application.create();
App.Session = Ember.Object.extend({
user: 'defaultUser'
});
App.User = Ember.Object.extend({
first: '',
last: ''
});
App.initializer({
name: 'session',
initialize: function(container, application) {
application.register('session:main', App.Session);
application.register('model:user', App.User, { singleton: false });
application.inject('route', 'session', 'session:main');
application.inject('controller', 'session', 'session:main');
application.inject('model:user', 'session', 'session:main');
}
});
App.IndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
var user = App.User.create({
first: 'bart',
last: 'jacobs'
});
console.log(this.get('session')); // returns `session` singleton
console.log(controller.get('session')); // returns `session` singleton
console.log(user.get('session')); // returns `undefined`
}
});
session
singleton accessible to every instance of theApp.User
class. I don't see why this should be a problem. The alternative is to have anApp.Session
singleton, but I prefer not to take that approach as it is considered a bad practice. – Bart Jacobs