Creating instances of objects with dependencies – Aurelia

Sometimes you want to create instances of objects with dependencies, which would normally have been created by the DI container within Aurelia.

Aurelia implements a Factory object which can be used to create instances out of the DI container on demand, for any of your objects:

import {Todo} from './todo';
import {Factory} from 'aurelia-dependency-injection';
import {EventAggregator} from 'aurelia-event-aggregator';

export class App {  

  static inject = [EventAggregator, Factory.of(Todo)];
  constructor(aggregator, todoFactory) {
    this.bus = aggregator;
    this.completedTodos = 0;
    this.newTodoDesc = '';
    this.todos = [];
    this.todoFactory = todoFactory;
  }

  addTodo() {
    if (!this.newTodoDesc) return;

    let todo = this.todoFactory();
    todo.description = this.newTodoDesc;
    this.todos.push(todo);
    this.newTodoDesc = '';
  }
}