我不明白.. 如果我可以使用 import
在 Aurelia 中,为什么我必须用 @autoinject()
连接构造函数而这一切?我确定我遗漏了一些东西,但是,据我所知,我可以随时使用我导入的模块。
import something from "whatever"
export class SomeViewModel {
activate() {
// use something
}
}
最佳答案
通常,在 Aurelia 应用程序中,您是 import
ing 不是 Something
的实例这是类(class)Something
.实际使用 import
中的任何内容ed,你需要它的一个实例。
import Something from 'whatever';
let something = new Something();
当您使用 Aurelia 的依赖注入(inject)系统时,您正在使用一种称为“控制反转”的设计模式。它不是你的类(或你)负责实例化它的依赖项,而是列出它拥有的依赖项,然后将依赖项的实例注入(inject)到它的构造函数中。
这有助于可测试性,因为现在您可以将依赖项的模拟实例传递给测试夹具中的类(请注意,在您的测试中,您的测试会将模拟传递给构造函数,而不依赖于 Aurelia 的 DI 容器)。这也允许您利用 Dependency Injection 容器配置为使用不同的对象生活方式(例如单例和 transient )创建依赖项的能力。
---编辑以从评论中回答OP的问题---
If I import a module defined as export default class Something into an aurelia view model using constructor injection, it does not need to be instantiated. It is an instance of the class Something.
这是因为 Aurelia 的依赖注入(inject)容器正在为您实例化一个实例。这就是您的代码如下所示的原因:
import {inject} from 'aurelia-framework';
import Something from 'somewhere';
@inject(Something)
export class Foo {
constructor(something) {
this.something = something;
}
//...
}
并不是
import Something from 'somewhere';
export class Foo {
constructor(Something) {
this.something = something;
}
//...
}
你是在告诉 Aurelia “我需要其中一个,请给我”,而 Aurelia 说:“当然,我已经创造了一个,或者我已经有一个了,就在这里。”
In other words, it appears that aurelia's constructor DI only works with class exports, and it does instantiate the class. It looks like if I want to import something like moment js into my aurelia view model, I should just continue doing things the way I've always done them (not using aurelia's DI). Does that sound correct?
这是对的。像
moment
这样的库给你一个函数来使用,而不是一个可以被 Aurelia 实例化的类。对于这些,您将像过去一样继续使用它们。
关于aurelia - 如果 Aurelia 理解 "import",为什么要使用依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37425881/