Association Injection or Dependency Injection?

一曲冷凌霜 提交于 2019-12-05 18:14:47

Because dependency injection is defined for coding not for design.

You can code an association with or without injection, but it is an association.

For example, in Java, the following codes show an association between a classe A and a class B implementing interface IB.

class A{ @Inject private IB b; ... }

or

Class A{ private IB b = new B(); ... }

First of all: I want to clarify some hints about Dependency Injection.

In Dependency Injection (see reference (4th paragraph)):

  • The client does not need to know how to construct the services.
  • The client does not need to know which actual services it is using.
  • The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services.

When we are using the dependency injection like below code:

class A {
    @Inject
    private IB b;

    //...
}

We do not actually know, which object of which class (that implements IB) was injected to b.

Maybe the injected class changes at runtime, maybe it changes because of some configurations that handled manually or automatically. Maybe it changes dynamically as period of time and etc.

So, we can not use an association between class A and other class (which class? or which object?)

Therefore, there is only dependency between class A and interface IB.

In small projects, maybe we have only one implementation of IB in our project. Or we do not have any mechanism to have dynamic injections. In this case, association may be used. However, in this case, there is no need to Dependency Injection.

To find good explanation from Martin Fowler and good example, see reference 2.

According to wikipedia:

Dependency injection is a technique whereby one object supplies the dependencies of another object. (...) Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

Note that the injection does not have to take place at construction, even if it often does.

A dependency relation is unidirectional: one object depends on another. The dependency injection has the goal of promoting one direction over the other (for example for inverting a dependency)

Associations are more general than dependencies: it can be unidirectional or bidirectional, depending on its navigability. So in most of the case, "injecting an association" would say nothing about the preferred direction: once the association is there, it could still be used in the wrong way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!