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

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

问题描述

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

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

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

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

需要-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天全站免登陆