Search code examples
aureliasystemjs

Aurelia: Dep. Injection on derived classes not possible? (or what am I doing wrong?!)


The scenario: I have two derived classes that both extend the ActionBase class as follows. I want to use DI for both derived classes. But both classes have different dependencies. That should be possible, right? So what am I doing wrong? In both cases the injected instances/modules are 'undefined'. Any help/hint appreciated.

/*
 * Base class for Actions
 */

export class ActionBase {

  type;

  constructor(type) {
    this.type = type;
  }
}





/*
 * Derived Class: InsertAction
 */

import {inject} from 'aurelia-framework';
import {ActionBase} from './ActionBase';
import {PomManager} from '../manager/PomManager';

@inject(PomManager)
export class InsertAction extends ActionBase {

  pomManager;

  constructor(pomManager) {
    super("insert");
    this.pomManager = pomManager;
    console.log("[InsertAction:constructor] pomManager: ", this.pomManager); // undefined
  }
}





/*
 * Derived Class: RenderAction
 */

import {inject} from 'aurelia-framework';
import {ActionBase} from './ActionBase';
import {AnotherManager} from '../manager/AnotherManager';

@inject(AnotherManager)
export class RenderAction extends ActionBase {

  anotherManager;

  constructor(anotherManager) {
    super("render");
    this.anotherManager = anotherManager;
    console.log("[RenderAction:constructor] anotherManager: ", this.anotherManager); // undefined
  }
}

Solution

  • It is supported. Look at this working example where Action1 and Action2 extend BaseAction and each take different dependencies.

    Here's an example: https://gist.run?id=0efabf77c649f41981dcde753fdc542c

    app.js

    import {inject} from 'aurelia-dependency-injection'
    import {Action1, Action2} from './classes'
    
    @inject(Action1, Action2)
    export class App {
      constructor(a1, a2){
        this.message = "look at console output";
        console.log("a1",  a1.dep.constructor.name);
        console.log("a2",  a2.dep.constructor.name); 
      }
    }
    

    classes.js

    import {inject} from 'aurelia-dependency-injection'
    export class Action1Dependency {}
    export class Action2Dependency {}
    
    export class ActionBase{
    
    }
    
    @inject(Action1Dependency)
    export class Action1 extends ActionBase{
      constructor(dep){
        super();
        this.dep = dep;
      }
    }
    
    @inject(Action2Dependency)
    export class Action2 extends ActionBase{
      constructor(dep){
        super();
        this.dep = dep;
      }
    }