加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果Aurelia理解“导入”,为什么要使用依赖注入?

发布时间:2020-12-14 05:00:22 所属栏目:百科 来源:网络整理
导读:我不明白..如果我可以在Aurelia中使用import,为什么我必须使用@autoinject()和所有这些连接构造函数?我确定我错过了一些东西,但是,据我所知,我可以随时使用我导入的模块. import something from "whatever"export class SomeViewModel { activate() { // us
我不明白..如果我可以在Aurelia中使用import,为什么我必须使用@autoinject()和所有这些连接构造函数?我确定我错过了一些东西,但是,据我所知,我可以随时使用我导入的模块.

import something from "whatever"

export class SomeViewModel {
    activate() {
        // use something
    }
}

解决方法

通常,在Aurelia应用程序中,您导入的内容不是Something的实例,而是Something类.要实际使用已导入的内容,您需要一个实例.

import Something from 'whatever';

let something = new Something();

当您使用Aurelia的依赖注入系统时,您正在使用一种名为“控制反转”的设计模式.它不是你的类(或你)负责实例化它的依赖项,而是列出它所依赖的依赖项,然后将依赖项的实例注入其构造函数中.

这有助于提高可测试性,因为现在您可以将依赖项的模拟实例传递给测试装置中的类(请注意,在测试中,测试会将模拟传递给构造函数,而不依赖于Aurelia的DI容器).这也是允许您使用依赖注入容器的能力配置为使用不同的对象生活方式(如单例和瞬态)创建依赖关系.

—编辑从评论中回答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的Dependency Injection容器正在为您实例化一个实例.这就是您的代码如下所示的原因:

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实例化的类.对于这些,你会像过去一样继续使用它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读