通过DI启用定制的模式

通过DI启用定制的模式

本文介绍了通过DI启用定制的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看内存网络API ,其中包含以下代码:

I'm looking at the implementation of in-memory-web-api and there is the following code:

@Injectable()
export class InMemoryBackendService {
  protected config: InMemoryBackendConfigArgs = new InMemoryBackendConfig();
            ^^^^^^
  ...

      constructor(
        @Inject(InMemoryBackendConfig) @Optional() config: InMemoryBackendConfigArgs
                                                   ^^^^^^
        ) {
        ...

据我了解,模式如下:

  1. 定义类属性并在不使用DI的情况下实例化依赖项
  2. (可选)注入依赖项

如果用户通过DI提供了修改后的依赖关系,则将注入该依赖关系,并且将实例化没有DI的默认依赖关系.我怀疑可能与HTTP模块中的RequestOptions类似.

If a user provides modified dependency through DI, it will be injected and the default one instantiated without DI will be overridden. I suspect something similar maybe with RequestOptions in HTTP module.

这是常见的模式吗?

编辑:

事实证明,in-memory-web-api并不完全是我要询问的模式.假设我有一个类A,该类使用可注入令牌B的类B的实例.因此,它们都已向根注入器注册:

It turns out that in-memory-web-api is not exactly the pattern I'm asking about. Suppose, I have a class A that uses instance of class B injectable with the token B. So they are both registered with the root injector:

提供者:[A,B]

现在,如果用户要自定义B,则可以使用相同的令牌注册自定义的版本,从而有效地覆盖了原始的B:

Now, if a user wants to customize B, he can register the customized version under the same token, thus effectively overrriding the original B:

providers: [{provide:B, useClass: extendedB}]`

这是在http模块中扩展RequestOptions的方式.

This is how RequestOptions can be extended in http module.

推荐答案

默认值不只是被覆盖. 大多数重要部分在这里

The default value isn't just overridden. The most important part here is

Object.assign(this.config, config || {})

没有它什么都不会发生.

Nothing would happen without it.

此模式不是特定于DI的,它是默认属性值的常用配方,类似于_.defaults.

This pattern isn't specific to DI, it is a common recipe for default property values, similar to _.defaults.

我会说InMemoryBackendConfig 默认实现在这里是无用的抽象.由于this.config总是与config合并,因此前者可能只是一个普通对象

I would say that InMemoryBackendConfig default implementation is useless abstraction here. Since this.config is always merged with config, the former could be just a plain object

  protected config: InMemoryBackendConfigArgs = { ... };

InMemoryBackendConfigRequestOptions使用此模式的复杂变体.是的,以最基本的形式可以做到这一点:

InMemoryBackendConfig and RequestOptions use complicated variations of this pattern. Yes, in most basic form this is how this can be done:

providers: [{provide:B, useClass: extendedB}]`

此模式已被AngularJS中的constant服务广泛用于配置对象,但是将B作为类而不是普通对象可以扩展原始值而不是替换它们.

This pattern is widely used by constant services in AngularJS for configuration objects, but having B as a class instead of plain object allows to extend the original values instead of replacing them.

这篇关于通过DI启用定制的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:26