辅助注射在Aurelia? [英] Assisted injection in Aurelia?

查看:102
本文介绍了辅助注射在Aurelia?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的构造函数有两个参数;一个是依赖,另一个是一个配置属性:

  @inject(Dependency)
class MyClass {
constructor(dependency,config){
}
}

如何利用Aurelia的依赖注入自动注入依赖关系,但允许类的使用者指定配置值?

解决方案

最后我创建了一个自定义解析器,这意味着代码很好,模块化,易于在其他类中使用。



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是类依赖关系的数组
/ /我们需要在他们有用之前解决它们
dependencies = Class.inject.map((dep)=> container.get(dep)),
//传递已解析的依赖项+ any新类的额外参数
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){
}
}


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

@inject(Dependency)
class MyClass{
  constructor(dependency, config){
  }
}

How can I make use of Aurelia's dependency injection to automatically inject the dependency but allow the class's consumer to specify the config value?

解决方案

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){
    }
}

这篇关于辅助注射在Aurelia?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆