Dependency Injection in Emberjs

I read some articles about Emberjs Dependency Injection(DI) and try to upgrade my old project food_ntpc to use DI. The pros of DI is to reduce gobal object and make code clean, testing easily. There are few changes.

before

I create a CategoryManager and put in FoodNtpc App.

category.js.coffee
1
2
3
4
5
6
class CategoryManager
  categorys: ->
    return categorys
  ...

FoodNtpc.CategoryManager = new CategoryManager

It’s very easy to access through FoodNtpc.CategoryManager everywhere. BUT it makes testing hardly and more coupling.

index_route.js.coffee
1
2
3
FoodNtpc.IndexRoute = Ember.Route.extend
  model: ->
    return FoodNtpc.CategoryManager.categorys()

after

Only the Ember.Object class can be registered. I change class CategoryManager to CategoryManager = Ember.Object.extend. Then create an initializer to register the CategoryManager in foodntpc:categoryManager naming. Set singleton to true because i want only one CategoryManager in system.

category.js.coffee
1
2
3
4
5
6
7
8
9
10
11
12
#class CategoryManager 
CategoryManager = Ember.Object.extend
  categorys: ->
    return categorys
  ...

#FoodNtpc.CategoryManager = new CategoryManager
Ember.Application.initializer
  name: 'categoryManager'
  initialize: (container, application) ->
    console.log 'register categoryManager'
    container.register('foodntpc:categoryManager', CategoryManager, {singleton: true})

Next, create another initializer to inject those dependency. We can use after or before to adjust initializer sequence.
In application.js line 6 means foodntpc:categoryManager is injected to IndexRoute and use CategoryManager reference. In line 7 means inject into all controller.

application.js
1
2
3
4
5
6
7
8
9
Ember.Application.initializer({
  name: 'injectModelManager',
  after: 'categoryManager',

  initialize: function(container, application) {
    application.inject('route:index', 'CategoryManager', 'foodntpc:categoryManager');
    application.inject('controller', 'CategoryManager', 'foodntpc:categoryManager');
  }
});

In IndexRoute, we use this.CategoryManager to access it.

index_route.js.coffee
1
2
3
FoodNtpc.IndexRoute = Ember.Route.extend
  model: ->
    return @CategoryManager.categorys()

Comments