Assisted injection in Aurelia?

前端 未结 2 1952
春和景丽
春和景丽 2020-12-24 08:50

I have a class whose constructor has two arguments; one is a dependency, the other is a configuration property:

@injec         


        
2条回答
  •  星月不相逢
    2020-12-24 09:17

    In the end I created a custom resolver, which means the code is nice and modular and easy to use in other classes.

    foo.js

    import {inject} from 'aurelia-framework';
    import {FooDependency} from './foo-dependency';
    
    @inject(Dependency)
    export class Foo{
      constructor(dep, cfg){}
    
      static useArgs(...args){
         return new Resolver(Foo, args);
      }
    }
    
    @resolver
    class Resolver{
      constructor(Class, args){
        this.Class = Class;
        this.args = args;
      }
    
      get(container){
        var Class = this.Class,
          // Class.inject is the array of the class's dependencies
          // we need to resolve them all before they're useful
          dependencies = Class.inject.map((dep)=>container.get(dep)),
          // Pass the resolved dependencies + any additional arguments to the new class
          args = dependencies.concat(this.args);
    
        return new Class(...args);
      }
    }
    

    needs-foo.js

    import {inject} from 'aurelia-framework';
    import {Foo} from 'foo';
    
    @inject(Foo.useArgs('my config'))
    export class NeedsFoo{
        constructor(fooConfigured){
        }
    }
    

提交回复
热议问题