When to use Dependency Injection

前端 未结 8 966
野性不改
野性不改 2020-12-01 00:19

I\'ve had a certain feeling these last couple of days that dependency-injection should really be called \"I can\'t make up my mind\"-pattern. I know this might sound silly,

8条回答
  •  隐瞒了意图╮
    2020-12-01 00:39

    I think that DI is worth using when you have many services/components whose implementations must be selected at runtime based on external configuration. (Note that such configuration can take the form of an XML file or a combination of code annotations and separate classes; choose what is more convenient.)

    Otherwise, I would simply use a ServiceLocator, which is much "lighter" and easier to understand than a whole DI framework.

    For unit testing, I prefer to use a mocking API that can mock objects on demand, instead of requiring them to be "injected" into the tested unit from a test. For Java, one such library is my own, JMockit.

提交回复
热议问题