What should be constructed through an IOC containe

2019-04-28 10:59发布

How do you determine which classes should be constructed through an IOC container, and which ones shouldn't. I've worked on projects with both extremes and it seems like interfaces should only be used when the classs specifies a specific technoliogy like logging or data access?

Where do people draw the line between the two?

2条回答
迷人小祖宗
2楼-- · 2019-04-28 11:10

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

查看更多
叛逆
3楼-- · 2019-04-28 11:14

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.

查看更多
登录 后发表回答