What should be constructed through an IOC container?

帅比萌擦擦* 提交于 2019-12-05 07:23:19

I don't draw any line - the more, the merrier.

What happens is that the more you can manage to split up your API in small units, the closer you get to the Single Responsibility Principle, because everything that hides behind an interface will have a tendency to do only one thing, and do it well.

By injecting interfaces into implementation that implement new interfaces that are injected into other types, etc. you end up with a very flexible structure where you can vary implementation details at almost any level, and each collaborator is pretty simple in itself.

With a good DI Container and some sensible conventions, the DI Container will automatically take care of most of the wiring for you, so the configuration doesn't have to be extreme.

Classes to be instantiated by the DI container (assuming one is used) should be those that implement a Separated Interface, and that need to be chosen at runtime depending on the execution environment.

You may then ask: which classes should implement a Separated Interface, and which should not? There are basically two reasons to create a new separate interface:

  1. You need to break a dependency between two parts of the system (just avoid doing it simply because you can).
  2. You will have multiple independent implementations (keep in mind it's normally easy to introduce a separate interface later through refactoring, so "what-if" thinking should be avoided).

For reference, see: http://martinfowler.com/articles/injection.html#SeparatingConfigurationFromUse

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