gpt4 book ai didi

javascript - Aurelia辅助注入(inject)?

转载 作者:可可西里 更新时间:2023-11-01 01:40:11 26 4
gpt4 key购买 nike

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

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

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

最佳答案

这里有一些选项:


选项 0:工厂解析器

foo.js

import {inject} from 'aurelia-framework';
import {FooDependency} from './foo-dependency';

@inject(FooDependency)
export class Foo {
constructor(dep, config) {
}
}

需要-foo.js

import {inject, Factory} from 'aurelia-framework';
import {Foo} from './foo';

@inject(Factory.of(Foo))
export class NeedsFoo {
constructor(fooFactory) {
let config = {};
this.foo = fooFactory(config);
}
}

选项 1:工厂

foo.js

import {inject} from 'aurelia-framework';
import {FooDependency} from './foo-dependency';

class Foo {
constructor(dep, config) {
}
}

@inject(FooDependency)
export class FooFactory {
constructor(dep) {
this.dep = dep;
}

makeFoo(config) {
return new Foo(this.dep, config);
}
}

需要-foo.js

import {inject} from 'aurelia-framework';
import {FooFactory} from './foo';

@inject(FooFactory)
export class NeedsFoo {
constructor(fooFactory) {
let config = {};
this.foo = fooFactory.makeFoo(config);
}
}

选项 2:子容器

foo.js

import {inject} from 'aurelia-framework';
import {FooDependency} from './foo-dependency';

export const configKey = 'config';

@inject(FooDependency, configKey)
export class Foo {
constructor(dep, config) {
}
}

需要-foo.js

import {inject, Container} from 'aurelia-framework';
import {Foo, configKey} from './foo';

@inject(Container)
export class NeedsFoo {
constructor(container) {
let config = {};
let childContainer = container.createChild();
childContainer.registerInstance(configKey, config);
this.foo = childContainer.get(Foo);
}
}

选项 3:蛮力

foo.js

export class Foo {
constructor(dep, config) {
}
}

需要-foo.js

import {inject, Container} from 'aurelia-framework';
import {FooDependency} from './foo-dependency';
import {Foo} from './foo';

@inject(Container)
export class NeedsFoo {
constructor(container) {
let config = {};
let dep = container.get(FooDependency);
this.foo = new Foo(dep, config);
}
}

关于javascript - Aurelia辅助注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com